HTML5: Data Attributes

HTML5 data attributes are a great alternative to classes and rel for storing data in an html tag.

Creating a Custom Attribute

Data attributes can be placed inside any type of tag and needs to follow the format of data-[desired_attribute]=”[value]” requiring at least one character following the dash.  Let’s look at an example:

Let’s say you have a Pinterest-like site that features a number of different images, and you want to be able to store certain attributes with each one, you could use data attributes as follows:

<img src="images/pug_puppies.jpg" data-category="cute animals" data-size="medium">

Using Data Attributes

You can access the content of your data attribute using javascript to do a number of things.  For example, if your html contains a series of award winning dogs, you can store what award each won in a data-award:

<img src="images/pug_puppy.jpg" data-award="Cutest">
<img src="images/toy_poodle.jpg" data-award="Best in Show">
<img src="images/lab.jpg" data-award="Most Agile">
<img src="images/Beagle.jpg" data-award="Loudest">

You can then use the data attribute to alert the award won each time you clicked an image:

$('img').click(function(e) {
   e.preventDefault();
   award = $(this).attr('data-info');
   alert(award);
 });

You can also store numbers in the data attribute (i.e. data-percentage, data-price, etc.) then use the information to help you sort.  The possibilities are endless.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>