jQuery.data() with HTML5 Custom Data Attributes

Sam Deering

This is how you might go about using the new HTML5 Custom Data Attributes feature available in HTML5 with the jQuery.data() function. It is very useful for adding data into a page and passing custom settings for DOM elements into JavaScript for some initialisation code at runtime.

HTML5 with Custom Data Attributes

Considering the following div I have added some random data attributes. It’s basically just prepend any identifier with “data-” and don’t include quotes on booleans.

<div class="widget" data-name="Sam Deering" data-fav-food="pizza" data-man=true data-noob=false>
    <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</div>
​

Using jQuery.Data();

Here is different ways to get the data from the DOM element using jQuery (in a document ready).

$('.widget').data('name'); // "Sam Deering"
$('.widget').data().name; // "Sam Deering"
$('.widget').data(); // Object { noob=false, man=true, favFood="pizza", more...}

//identifier with mutiple words (ie data-fav-food="pizza")
$('.widget').data('favFood'); // pizza

//identifier with boolean value (ie noob=false)
$('.widget').data('noob'); // false

Try it yourself

I created a jQuery.Data() jsFiddle for you to play around with the data attributes and do some testing.

Basic Example

In the following example I are using the data attibutes to set the title, size, position and behaviour of a div element. The first div has also been given drag and resize privileges.

widgets-windows

HTML

<div id="div1" class="widget" data-left="10" data-top="130" data-width="300" data-height="350" data-title="Div 1" data-drag=true data-resize=true>
  <p>Maecenas faucibus mollis interdum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p>
  <p>Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Aenean lacinia bibendum nulla sed consectetur. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. </p>
  <p>Maecenas sed diam eget risus varius blandit sit amet non magna. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Cras mattis consectetur purus sit amet fermentum. Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. </p>
</div>

<div id="div2" class="widget" data-left="360" data-top="130" data-width="300" data-height="200" data-title="Div 2">
  <p>Maecenas faucibus mollis interdum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed diam eget risus varius blandit sit amet non magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p>
  <p>Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Aenean lacinia bibendum nulla sed consectetur. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. </p>
  <p>Maecenas sed diam eget risus varius blandit sit amet non magna. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Cras mattis consectetur purus sit amet fermentum. Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. </p>
</div>

JQUERY

//loop for each
...

//defaults settings (get from data attributes)

var d_all       = elem.data(),
    d_title     = (d_all.title) ? d_all.title : "Div Title";
    d_left      = (d_all.left >= 0)  ? d_all.left : 50,
    d_top       = (d_all.top >= 0) ? d_all.top : 50,
    d_w         = (d_all.width >= 0)  ? d_all.width : 600,
    d_h         = (d_all.height >= 0)  ? d_all.height : 350,
    d_resize    = (d_all.resize)  ? d_all.resize : false,
    d_drag      = (d_all.drag)  ? d_all.drag : false;

//create the dialog using settings

elem.dialog(
{
    "title": d_title,
    "height": d_h,
    "width": d_w,
    "position": [ d_left, d_top ],
    "resizable": d_resize,
    "draggable": d_drag
});

Further reading into jQuery.data();

Where does this data get stored?

You can also pass objects when setting new data instead of key/value pairs. An object can be passed to jQuery.data instead of a key/value pair; this gets shallow copied over onto the existing cache.

//http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js Line: 1741

if ( typeof name === "object" || typeof name === "function" ) {
  if ( pvt ) {
    cache[ id ] = jQuery.extend( cache[ id ], name );
  } else {
    cache[ id ].data = jQuery.extend( cache[ id ].data, name );
  }
}

Where does this data get stored?

jQuery data() is stored in a separate object inside the object’s internal data cache in order to avoid key collisions between internal data and user-defined data.

//http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js Line: 1753

if ( !pvt ) {
  if ( !thisCache.data ) {
    thisCache.data = {};
  }

  thisCache = thisCache.data;
}

What about boolean and integer types?

Play around with it: http://jsfiddle.net/KMThA/3/

<strong>HTML</strong>
<div class="widget" data-booleanv=true data-stringbooleanv="true" data-numberbooleanv=1 data-intv="365" data-intv=365 data-stringintv="365" data-floatv=365.59 data-stringfloatv="365.59">
    <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</div>
​
<strong>jQuery</strong>
var customData = $('.widget').data();
console.dir(customData);

$.each(customData, function(i, v)
{
    console.log(i + ' = ' + v + ' (' + typeof(v) + ')'); // name = value (type)
});
​

Output

boolean-int-types

Thanks for reading, hope you all start using the new HTML5 data storage methods!

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Pingback: 9 jQuery Image Manipulation Plugins | jQuery4u

  • anant salgaonkar

    i got a way to inject it using attr function but can it be passed inside directly

    $(”,{
    text: “(” + (i+1) + “,” + (j+1) + “)”,
    class:”elementbox”,
    id: “id-” + (i+1) + “-” + (j+1),
    }).appendTo(‘#elementCotainer’).attr(‘data-a’, ‘foo’) ;

  • Jimmy

    Random question but what Sublime theme are you using here?

  • http://ramesh-vishwakarma.com Ramesh Vishwakarma

    Helpful article to work with HTML5 custom data attr. Thanks Sam.