Placed in: Home arrow Programming arrow Webdesign arrow HTML5 data-* attributes are great and you know it
HTML5 data-* attributes are great and you know it

Like I said in my previous article, all information about HTML5 is way too big to put into one blog article. We first looked at what HTML5 microdata can do for us, and today we'll dive into another feature W3C added to their HTML specification. It's called custom data attributes (by developers mostly referenced as data-* attributes), and I'll explain what it is and what problems it fixes for us.

HTML5 data-* attributes

The data-* attributes are extremely useful, especially for JavaScript developers. W3C describes the use of these kind of attributes as: Embedding custom non visible data to your HTML. But why would you need it? Let's take a dive into this new HTML specification. Although this article has a strong focus on jQuery, I assume you understand it counts for any other library and (of course) JavaScript itself.

Uses of technologies

Chris Coyier created this useful overview for the correct use of the several webdesign technologies:

Web Technologies

Now let's focus on two techniques Chris points out here: HTML and JavaScript. Keep their appropriate use in mind, since it's very important to know the difference.

JavaScript plugins

JavaScript plugins are great. jQuery has loads of official jQuery plugins which extend the capabilities of the framework just that little bit further (I wrote some plugins for jQuery too). Since you want the plugin to be used by loads of people, you make it easy to use and as flexible as possible.

Although jQuery allows options to be used to change the behaviour of the plugin, sometimes you need to put data inside the HTML for it to make it work. For example, take a look at this piece of code:

HTML

 
<img class="pic-0" />
<img class="pic-1" />
<img class="pic-2" />

 
for(var i = 0; i < $("img").length; i++) {
   $(".pic-" + i).doStuff(); // Do something   
}

JavaScript

I know this isn't the best example I came up with, but that isn't the goal of this article. The plugin loops through all the elements starting with the pic- class and does something with them (for example: Arrange them according to their index). But why it this o-so-very-wrong?

The main problem here, is the mis-use of the class attribute; That should mainly be used as a reference for CSS. And the use of prefixes (in this case: pic-) is just extremely dirty. But let's take a look at another example for creating tooltips:

HTML

 
<p>
   This is the actual text
   <span>This is the tooltip</span>
</p>

 
$("p span").hide();
$("p").hover(function() {
   $("span", this).show();
});

JavaScript

So here we "hide" the information stored in the tooltip inside a span-element (hiding could be done with CSS too). When we hover the paragraph, the tooltip will show it's contents. But what's wrong with this solution?

Once again, we mis-use something here. This time, it's the span-element that is out of place. We manually need to hide it and it doesn't "feel" right at that place. But how should we tackle these kind of problems, the right way?

The jQuery solution

For these kind of problems, jQuery already has a pretty nifty solution. Since we don't want our HTML-elements or attributes to be mis-used, we can dynamically add data to the DOM using the .data() API. This allows jQuery developers to add the data they want to the HTML elements, without abusing the HTML itself. Let's take a look at how the two previous examples could be re-written using the .data() API.

HTML

 
<img />
<img />
<img />

 
var i = 0;
$("img").each(function(){
   $(this).data("iterator", i); // Store data
   i++;
});
 
$("img").hover(function(){
   alert($(this).data("iterator")); // Retrieve data
});

JavaScript

Did you see that? We don't have any dirty class attribute mis-use anymore, since we can simply iterate over the HTML element and add the index dynamically (I know the index() method would be better in this case, but just for the sake of the example, I kept it simple). Looks like a very good solution for our problem we had before!

But now for the tricky part: How would you re-write the tooltip example to use the data() API? You don't want to store the tooltip text inside the JavaScript file. If you do this, it would mean that you would update the JS file each time you want to add a new tooltip. Also, you would store your content inside JavaScript instead of the place where it belongs: The HTML. So, how should we fix this problem?

Bring in the data-*

The custom data attributes give us a very clean solution for this problem. We can now store any data and add it to the HTML as an attribute, as long as it starts with data-. Let's take a look at how we could have re-written the two previous examples, but now using the custom data attributes.

 
<img data-index="0" />
<img data-index="1" />
<img data-index="2" />
 
<p data-tooltip="This is the tooltip">
   This is the actual text
</p>

HTML

I know the first example looks very silly, but I'll come to that later. The second one, on the other hand, is pretty cool! We now have the appropriate place to store that kind of information. Another upside, is that it's hidden by default and we can easily retrieve it using JavaScript to display the tooltip. When using jQuery, you could simply retrieve the value using the .attr() method, like this:

JavaScript

 
   var index = $("img").attr("data-index");
   var tooltip = $("p").attr("data-tooltip");

Take note the .customdata() plugin is a lot more flexible for custom data attributes.

But now back to the images. Although the data-index isn't that useful, we can make a lot more use of the custom data attributes. Another advantage is that we are not limited to one data attribute! We can add as many as you want, as long as they all have a unique name. Check out the following HTML:

 
<img alt="My alt text"
   data-longdescr="My long description"
   data-geo="Location I took the picture"
   data-cam="The type of camera I used"
   data-time="The time I took the picture" />

HTML

Did you see that? I'm suddenly capable of adding loads and loads of more data to one single image. Imagine how you would write this when you couldn't use the custom data attributes? Logically, it probably wouldn't make as much sense as above. Now you can use these attributes to display them using JavaScript. This is the kind of power you get when using custom data attributes.

Conclusion

In my opinion, the data-* attributes is one of the coolest and (for the developers) most useful features there is. We're now able to store data inside the HTML without any dirty hacks, or storing it in the JavaScript. Although it has some limitations (for example: You can only place text inside the attributes, and not more HTML elements), I think it's a pretty nice solution for the problems described above.

What do you think? Have you ever encountered a problem like described above? If so, do you like the data-* attributes solution proposed in HTML5? Feel free to share!

Further reading


Tags:  html5 data custom attribute tutorial

Interested in this topic? You might enjoy another article I've written called

Did you like this article? Subscribe to my feed or email to keep updated on new articles.

Spread the word and submit to:
Digg!Reddit!Del.icio.us!Facebook!StumbleUpon!
Comments
Add NewSearchRSS
Jon - Browser support   2010-10-11 12:36:01
Gravatar image Thanks for this! Presumably we can use the data-* attributes in every browser as well?
Andrey Luiz - Very good.   2010-10-11 16:17:05
Gravatar image Yeaah.
Very interesting.
Congratulations for the post.
The data attrib is very usefull.
Giacomo Colddesign - Great article   2010-10-11 18:26:06
Gravatar image An other great article, thanks! But what a bout the browsers that don't support HTML5?
Marco - Backward compatible   2010-10-12 06:51:36
Gravatar image @Jon & @Giacomo:
You guys are right, I totally forgot to mention this in the article.

The data-* is backward compatible and will (probably - haven't tested it) in every browser. It's not really HTML5 specific, but when using the HTML5 doctype, using the data-* types will give you valid HTML.

Older browsers will simply see it as "yet another attribute" that can be used like any other attribute!
Giacomo Colddesign - Thanks   2010-10-12 09:02:50
Gravatar image ok.. thanks for answer!
Curt   2010-10-13 13:21:31
Gravatar image I've been making up my own attributes for js to store/retrieve data to/from for many years. How is this different? It validates?
Ludvig Ludvig Lindblom   2010-10-13 14:36:54
Gravatar image Yes, the difference is it validates.

It works just like it does when adding data to self-made attributes.
A common way to tackle this earlier, from what I've seen, is using the rel-attribute. Allthough that only gives you one place to store it the technique is the same.
droope - Awesome   2010-10-15 12:29:00
Gravatar image really cool. Definitively going to use it
mh   2010-10-20 20:20:01
Gravatar image Check the jquery 1.4.3 release notes for some data related improvements:

Quote:


For example, given the following HTML:



All of the following jQuery code will work:

$("div" ).data("role" ) === "page";
$("div" ).data("hidden" ) === true;
$("div" ).data("options" ).name === "John";

Marco - Did not know!   2010-10-20 20:22:10
Gravatar image Thanks mh - I didn't even notice that yet! Just checked the release notes, and they indeed included some sweet data-* stuff to jQuery. Gotta love it!
Ben Newto - big improvement   2010-10-26 02:20:50
Gravatar image I have a large ecommerce site. This has allowed me to simplify so much code. When listing products where each have options that call javascript functions, I used to have to pass the item number in the function so the function knew which item item to work with.

Now I can store the item in a data attribute and get it with jquery. Much cleaner in both the javascript and the html.

Thanks for the great article.
David   2011-09-24 02:23:30
Gravatar image Learn a lot,Thanks
wejw2   2012-04-06 08:26:57
Gravatar image Their mission, and the valley of surveillance of the former is called the wild, http://www.louboutinshoesuksale.co.uk/ where once found the poaching, immediately people and won the spoils, real-time processing.
robot dude - That dude wejw2 is a robot!   2012-05-30 06:25:57
Gravatar image wtf does that last comment mean.

that dude is a robot churning out meaningless text from a book and mashing it up.

remove the scoundrel.
vol7ron   2013-01-20 17:04:59
Gravatar image I'm sorry. I think this is a good attempt, but the jQuery code you used is not good and the examples are not consistent, so you can't see any benefit of the data-* attribute; especially over accessing information through $.data(). It's because of the poor examples, that I wouldn't advise people to read this article, but I think with some patching, that could be changed.

Also, there's no date when this article was written, so you can only guesstimate based on the comments' timestamps.
MC   2013-03-05 22:48:00
Gravatar image @vol7ron have to disagree with your comment. I found the article very useful and examples very helpful.
Anna   2013-04-03 08:47:20
Gravatar image Thanks for the great article. I use it in my site: http://putinpussy.com/
vick   2013-04-12 17:19:10
Gravatar image HTML Attributes are property of the elements which may have values and these attribute values are always enclosed in quotes. It
Read more...
Name:
Email:
  Gravatar enabled.
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
 
Security Image
Please input the anti-spam code that you can read in the image.
Unsubscribe from e-mail notifications.
 
< Prev   Next >
Subscribe

Subscribe to Marcofolio