Advertisement

All You Need to Know About the HTML5 Data Attribute

by

This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

This post is part of a series called Strange and Unusual HTML Tags.
Quick Tip: Consider Wrapping Your Code With a “figure” Element
Explaining the “Details” and “Summary” Elements

The HTML5 data attribute lets you assign custom data to an element. This article looks at how to use it and provides examples of when it would be ideally used.


Introduction

Prior to HTML5 we had to rely on using 'class' or 'rel' attributes to store little snippets of data that we could use in our websites. This sometimes led to problems and could cause conflicts between the styling and functionality of websites. The advent of HTML5 introduced a new attribute known as 'data'. In this article I'm going to be looking at some examples of how we would use this attribute as well as how it should be used correctly.

As websites are becoming more data driven and app-like, they are starting to hold more data about specific elements. Take, for instance, if we were creating an audio application. We might have standard markup such as:

<audio controls="controls">
  <source src="track1.mp3" type="audio/mpeg" />
</audio>

The above markup is perfectly acceptable but sometimes we might want to store more information about each track other than the source. For example we may want to be able to assign other specific track information such as the duration, tempo and artist. We could do this by assigning custom data-attributes to each audio source such as:

<audio controls="controls">
  <source src="track1.mp3" type="audio/mpeg" data-duration="1min5secs" data-tempo="125bpm" data-artist="The Beatles" />
</audio>

By providing these custom data attributes we can then perform tasks such as searching, filtering or grouping them within our application by duration, tempo or artist using their associated values.


How to Use the Data-attribute

The name of a data attribute must begin with the string 'data-' and must contain at least one character after the hyphen using any HTML naming convention.

The W3C specification for data-attributes states that:

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

This means that we should only use that data internally within our application and it should not be used for displaying the information to our users. It's also important to note that you can assign any number of custom attributes to an element with any value.


When Should I Use the Data Attribute?

We've already looked how you might use the data attribute but so that you gain a clear understanding, let's look at a few more examples.

Luckily Webdesigntuts+ have already covered some detailed tuts on some good use case examples. One of the tuts looks at how you might use them to style and display menu notification bubbles by assigning the notification item in an anchor tag. This time the data attribute is used to indicate the bubble value of the notification bubble.

<a href="#" class="pink" data-bubble="2">Profile</a>

In another quick tip we can also see how it is used as part of the markup for a tooltip

<a href="#" class="tooltip" data-tip="this is the tip!">This is the link</a>

This time is used to show the text for the tooltip.


When Shouldn't I Use the Data Attribute?

We shouldn't use data attributes for anything which already has an already established or more appropriate attribute. For example it would be inappropriate to use:

<span data-time="20:00">8pm<span>

when we could use the already defined datetime attribute within a time element like below:

<time datetime="20:00">8pm</time>

Data attributes should not be used as an alternative to meta data or micro formats. Micro formats are designed primarily for humans and were introduced to give our markup context. For example if you have a Vcard providing contact information about an individual or organization then you would give it a class of 'vcard' to let machines understand that this is contact information.

Using micro formatting you should use your markup as

<div class="vcard">
 <span class="fn " >Aaron Lumsden</span>
</div>

instead of using the data attribute such as

<div class="vcard">
 <span data-name="Aaron Lumsden " >Aaron Lumsden</span>
</div>

To learn more about micro formats you can visit Mircorformats.org.


Using Data Attributes With CSS

Once we've implemented data attributes within our HTML markup we are able to target them using CSS. It's important to note that you shouldn't use data attributes directly for the use of styling, although in some cases it may be appropriate. Targeting data attributes in CSS is similar to targeting other attributes, you can use them simply like this:

[data-role="page"] {
  /* Styles */
}

If for example you are creating a cross device friendly site or app then you may want to target some specific content that you should only view on mobile. Take the following markup

<div data-role="mobile">
Mobile only content
</div>

Using CSS you could then hide all the mobile only pages when being viewed on a desktop.

div[data-role="mobile"] {  
  display:none;  
}

Although it's not advised to hide content based on viewing device, there may be some instances where it is appropriate. You should base this on each individual circumstance and case.

It's also possible to use the data from the attribute and display it through CSS. Although the specification says that you shouldn't use the data from the custom attribute to display to your users it can be done, and in some circumstances may prove the best method. This is how it's achieved.

<div class="test" data-content="This is the div content">test</div>​

In CSS you would then use the ':after' pseudo element (or some other generated content) and use the attribute as part of the 'after' content like so:

.test {
  display: inline-block;
}

.test:after {
  content: attr(data-content);
}

This would then display 'This is the div content' in the '.text' div. 


Using Data Attributes With jQuery

Now we've looked at how you can target elements with the data attribute using CSS, let's look at how you can get hold of that data using jQuery.

Note: Processing the data is out of the scope of this tutorial, as this tutorial is specifically aimed at front end developers and designers.

There are a few ways we can get the data from the element using jQuery. Let's look at some of those.

<a href="http://www.google.com" class="button" data-info="The worlds most popular search engine">Google</a>

If we had an anchor tag, like the one above, that had a data attribute of data-info then we can access that data in the same way that we would get any other attribute value.

$('.button').click(function(e) {
   e.preventDefault();
   thisdata = $(this).attr('data-info');
   console.log(thisdata);
 });

You can test this by opening up the js console in your web inspector, then hitting the link..

The great thing about the data attribute is that we can also use it to provide json data like this.

<a href="google"  class="button" data-info='{"foo":"bar"}'></a>

Using jQuery we can get this data using the jQuery's data object method.

$('.button').click(function(e) {
   e.preventDefault();
    thisdata = $('div').data('info').foo;
   console.log(thisdata);
 });

The above example would then log "bar" to the console log.


Cross Browser Support

I know that before you get too giddy about using this new attribute you're going to want to know which browsers support it and when can you start using it. Well the good news is that it's well supported in all modern browsers. Anything that supports HTML will be able to access the data attribute. If you're using the attribute for styling purposes as well as to access the data (use with caution) then the browser will need to support CSS3 selectors.

The even better news though is that all browsers (even IE7) let you already use the data-* attribute on elements and if you're using jQuery 1.4 or above then you can access the data using jQuery's data object. However, if you're just using JavaScript then you will have to access the data using JavaScript's 'getAttribute' method.

For the full list support of the dataset you can check out canIuse.com.


Conclusion

As websites and web apps become more complex and start to hold more information and data, this new attribute is definitely a welcome addition to the toolbox. I've used it in quite a few real world examples now and have found it a very useful way to provide a more responsive (speedier) website as data that would have otherwise have had to be pulled in from the server can now be generated in the markup and used when necessary.

To summarize, if you stick to the following three rules, then you can ensure that you are using the new attribute in its most effective and semantic way.

  1. Only use it for internal use on your website/app. It shouldn't, for instance, be used in an XML/RSS feed for use on external websites or apps.
  2. Don't use it just for CSS styling.
  3. Don't use it to replace an existing attribute or element that would be more semantic or appropriate.

Now that you have a deeper understanding of the HTML5 data attribute and how it can be used, I encourage you to start implementing it in your projects today.

Have you used it in any real world examples? What scenarios have you used it in? Is it saving you time or is there anything that you'd like to see extended on with this attribute? Let me know in the comments below.

Advertisement