what does jQuery data() function do

Its really useful for associating various objects, strings, arrays, etc with a DOM element. Here is a fun hypothetical use:

$(document).ready(function(){
   $("a").each(function(index, el){
      if(index % 2 == 0) 
         $(this).data('coolColor', 'Orange'); // Set the data
      else 
         $(this).data('coolColor', 'Purple'); // Set the data
   }).click(function(e){
      alert($(this).data('coolColor')); // Retrieve the data
      e.preventDefault();
   });
});

This would select every a tag, and set Orange if its odd, or Purple if its even. This is not the most optimal way to write this code if this is what you really wanted to do, but it does illustrate how to use the .data() function.

You can also use it to store objects:

$("#header").data('headerSettings',{
   color: "red",
   cost:  "$25.00",
   time:  1000
});

Now you could access that data anywhere else on the page:

$("#header").data('headerSettings').color;

Leave a Comment