jQuery: attaching functions to elements with data()

With the jQuery data() method we can attach any kind of data to a jQuery element. This means that we can even attach functions and methods to elements. The basic syntax of the data() method allows us to specify the name of an object literal where we can attach our data. It is as follows:

element.data('objectName', {property: value, ...});

Our object is now attached to the jQuery element of our choice. We can access later this object as follows:

element.data('objectName').property

So far we've used simple properties, but we can attach methods as well:

element.data('objectName', {
  method: function() {
  
    alert('OK');
  
  }
 }
);

We can invoke this method as a normal object method:

element.data('objectName').method(); // alerts 'OK'

Since our method is now attached to the element, we can invoke it wherever we want in our code. Let's do an example: here's how to animate an element using the data() method:

$(function() {

  $('#test').data('test', {
  
  
  test: function() {
  
    var interval = setTimeout(function() {
    
      $('#test').animate({
        width: '+=20px',
        height: '+=20px'
      }, 500, function() {
      
        $(this).animate({
          width: 100,
          height: 100
        }, 500);
      
      
      });
      
      setTimeout(arguments.callee, 1000);
    
    
    }, 25);
  
  }
  
  });
  
  
  $('#test').data('test').test();


});

You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.