jQuery and Data Method

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:

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.

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.