Quantcast
Channel: html - Broken Links
Viewing all articles
Browse latest Browse all 12

Data Attributes in HTML and jQuery

$
0
0

Sometimes the existing HTML attributes aren’t sufficient for describing an element’s content. We can use class, ref, rel, title and more, but even so there are occasions where that’s not enough. HTML5 addresses this problem with the introduction of Data Attributes, which allow you to add simple metadata to individual elements, largely for the purpose of providing information to make JavaScript functions easier.

The syntax is a key:value pair, with the key being a keyword prefixed with data–, like so:

<div data-foo="bar"></div>

Note that this is not intended to compete with or replace Microformats or RDFa; data attributes were developed only to store custom data [about an element] when there is no more appropriate attribute or element available.

jQuery introduced support for data attributes in version 1.4.3, which was released in October 2010. You use the existing data() method to get and set values. Getting a value involves just using the keyword, as in this example which operates on the markup above:

var baz = $('div').data('foo');

This would set the value of ‘bar’ to the baz variable. jQuery’s implemenation is so clever that the variable will take on the correct value type — string, number, boolean — automatically. In the example above it would be a string, but given markup like this:

<div data-retail="3.99"></div>

The value of the variable would be provided as a number type. You can also use JSON syntax in data attributes, like so:

<div data-foobar='{"foo":"bar"}'></div>

Note that the attribute uses single quotes while the key:value pair inside are in double quotes; this is required to be valid JSON syntax. To access this with jQuery, just add the key name as an object at the end of the string:

var baz = $('div').data('foobar').foo;

This will once again instruct the variable baz to have the value ‘bar’.

flattr this!


Viewing all articles
Browse latest Browse all 12

Trending Articles