jQuery’s Data Method – How and Why to Use It

jQuery’s Data Method – How and Why to Use It

jQuery’s data method gives us the ability to associate arbitrary data with DOM nodes and JavaScript objects. This makes our code more concise and clean. As of jQuery 1.4.3 we also have the ability to use the method on regular JavaScript objects and listen for changes, which opens the doors to some quite interesting applications.

The Basics

You can call the data method on a jQuery object, or you can use the $.data() function instead.

// Using the data method:
$("#myDiv").data("key","arbitrary value");

// Using the data function:
$.data($("#myDiv").get(0),"key","arbitrary value");

The data function is a low level implementation, and is actually being used by the method call behind the scenes. The method call is also more convenient, as it allows you to include it as a part of a chain.

Also, notice that you need to pass a DOM element as the first parameter of $.data, and not a jQuery object. This is why in this article, we are going to concentrate on using the method call instead.

When you use the data method, you need to pass two parameters – a key and a value to be stored. The key has to be a string, and the value can be any data structure, including functions, arrays and objects. There is an alternative syntax, in which you pass an object as a single parameter:

// Passing an object:
$("#myDiv").data({"name":"Stevie","age":21});

// This is the same as:
$("#myDiv").data("name","Stevie").data("age",21);

Now that you’ve inserted your data, you can read it by calling the data method with a single parameter – the key:

var theValue = $("#myDiv").data("age"); // 21

You can access the data everywhere in your script. It doesn’t matter what the selector is, as long as it is the same element, you will get the same value you’ve put in:

// Given that myDiv is the first div in the page:

var theValue = $("div:first").data("name"); // Stevie

$("div:first").click(function(){
	alert($(this).data("age"); // 21
});

As of jQuery 1.4.3 HTML5 data- attributes are also made available via the data method. This means that if you have an element like this:

<img id="img1" data-internal-id="221" width="100" height="100" />

You can access the data-internal-id attribute by just calling $("#img1").data('internal-id'), which is really useful in AJAX applications. We also used this technique in last week’s tutorial – Making Better Select Elements with jQuery and CSS3.

Using the Data Method on JavaScript objects

You may find it surprising that you can use the data method on regular JavaScript objects. This functionality has been around for some time, but with jQuery 1.4.3 it opens the doors to some useful applications.

var myObj = {};
$(myObj).data("city","Springfield");

What the snippet above does, is actually create a city property on the object. But why not just set myObj.city = "Springfield" yourself? Because the data method triggers a number of useful events you can listen for:

var progressBar = {};

$(progressBar).bind('setData',function(e,key,value){
    switch(key){
        case "percent":
            $("#progress").width(value+"%");
            $("#percentText").text(value+"%");
            break;

        case "color":
            $("#progress").css("color",value);
            break;

        case "enabled":
            $('#progress').toggleClass("active",value);
            break;
    }
});

$(progressBar).data("enabled",true).data("percent",21).data("color","green");

// You also have easy access to the current values:
console.log(progressBar.enabled);    // true

In the fragment above, we use the data method to create a simple API with which we can update a progress bar on screen. The best part of it is that at any given time you can just take a peek at the progressBar object and get the current values.

There are two other events that are triggered when using the data method on a plain object:

  • getData – triggered before data is read from the object. You can use the return statement within the event handling function to override the value. Can be used to run calculations behind the scenes;
  • changeData – triggered whenever data is set or changed. It is used in the jQuery datalink plugin and allows you to bind a form to a JavaScript object and access the form fields as properties of that object. This way you don’t have to deal with reading and setting values, which is quite a burden especially in longer forms. You can see it in action in the demo page.
The jQuery Data Method & Data Link Plugin Demo

The jQuery Data Method & Data Link Plugin Demo

Behind the Scenes

Internally, jQuery creates an empty object (called $.cache for the curious), which is used to store the values you set via the data method. Each DOM element you add data to, is assigned a unique ID which is used as a key in the $.cache object.

jQuery does not store only user-created data in that cache. It also stores internal information and the event handling functions that you attach with live(), bind() and delegate(). Having centralized data storage makes jQuery’s codebase much more robust and bug free, something that we all can benefit from.

To Wrap it Up

The data method is just one of jQuery’s numerous utilities, which make the life of the web developer easier. Combined with the rest of the library’s abilities, it adds up to a solid foundation we can build upon.

Join our newsletter and get our PSDs!21,326 people learn about HTML5, JS and more. Join them!

by Martin Angelov

Martin is a web developer with an eye for design from Bulgaria. He founded Tutorialzine in 2009 and it still is his favorite side project.

♥ 21,326 developers love it

17 Comments

  1. Tiarê Balbi says:

    Very good!!!

  2. darkgaro says:

    Nice tutorial, I was wondering about the performance of using data method. Is there any performance penalty ??

    1. Martin Angelov says:

      Getting a value with data() requires a lookup of the DOM element's unique ID (which is defined as an expando property), after which jQuery does a lookup in the $.cache object.

      It cannot possibly be as fast as using plain variables, but for attaching data to a specific element this is optimal.

      So the short answer is that it depends on what you'll use data for. Performance might become a problem only when using the method in heavy loops. But even then there is a workaround. Just cache the data object:

      var obj = $('#myDiv').data();   // you can access data('prop') as obj.prop 
      
      for(var i=0;i<1000000;i++){
          // do something with obj
      }
      
  3. Vaanres says:

    very useful, i have learned a lot

  4. Joey says:

    Useful tot,I often forget to use this method...

  5. Great article.. thanks for sharing..!

  6. Beben Koben says:

    so usefully, thats briliant idea, thanks a lot master
    \m/

  7. Nice explanation of .data(). Will probably come in handy one day.

  8. Ah jQuery ........ the reason to venture off the server when programming :)

  9. marrcou says:

    i still dont get it? whats the point in doing it this way? so if i write something like:

    var myObj = {};
    $(myObj).data("title", "My Object");

    can i still access it like `myObj.title` or is it hidden in the jQuery cache? What if I do have some data I don't want to be simply written to the attributes of the tag? Is that when you use this function?

    I really don't see the benefit of using this over just a plain javascript object. Am I missing something?

  10. Nick Tulip says:

    nice demo. I would like to see the demo expand into an actual implementation of the progress bar.

  11. I am unfamiliar with the usage of "JSON.stringify(obj).replace". Would you explain what is going on here or point me to a tutorial.
    Thanks!

  12. William Rouse says:

    The first button does not work with jQuery 1.61.
    What's changed?

  13. Eric says:

    Thanks for the tutorial!

    There's a missing ending parenthesis on this line:

    alert($(this).data("age"); // 21

  14. Svetlana says:

    Thank you for a great article and useful tips, guys!

  15. Adam Fullen says:

    Great example! I was not aware of the events associated with the data() method prior, will be sure to use these now.

    One of the important things about the jQuery data() method is that it will acceppt anything that JavaScript does. I have been using it to simplify code writing for event handlers related to cached buttons with unique actions:

    var cache = {};
    cache.obj1 = $("obj1", document).data('CLICK_METHOD', function1Name);
    cache.obj2 = $("obj2", document).data('CLICK_METHOD', function2Name);
    cache.objGroup = obj1.add(obj2);
    
    objGroup.on("click", function(e){
      e.preventDefault();
      $(this).data('CLICK_METHOD').call(param);
    });
    
    var function1Name = function(param){
      // do function 1 stuff
    };
    var function2Name = function(param){
      // do function 2 stuff
    };
    
  16. Robin says:

    Helpful thanks for the tips.

Add Comment

Add a Reply

HTML is escaped automatically. Surround code blocks with <pre></pre> for readability.
Perks:   **bold**   __italics__   [some text](http://example.com) for links