Cheesetoast

Brain Food for Web Developers

HTML5 Logo

Custom Data Attributes in HTML5

One of the new abilities of HTML5 is that it allows you to add a custom data attribute to your markup. This is useful for when you want to include some metadata in your markup. Previously people could use class names to accomplish this but this isn’t really semantic.

The new data attribute look like this:

<button data-file="stylesheet1">Style 1</button>

The attribute must be prefixed with “data-” and should be all lower case.

Data Attribute in Action

Let’s say you’re using a button to change the style of your entire page by redirecting to a new css file using some javascript code.

<button data-file="stylesheet1">Style 1</button>
<button data-file="stylesheet2">Style 2</button>

Now you can use the following jQuery code to extract the meta data from your new data attribute:

$('button').click(function(){
   var stylesheet = $(this).attr('data-file');
   $('link').attr('href', stylesheet + '.css');
});

For more information on the custom data attribute head on over to HTML5 Doctor.

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.