Manage HTML5/JS metadata using custom data attributes


HTML5 introduces custom data attributes for tags - these are attributes that starts with "data-". These will be treated as a storage area for private data.

If you rely on element class names or rel attributes to store arbitrary snippets of metadata and still look for "hooks", these data attributes will come as a relief.


Prefixing the custom attributes with data- ensures that they will be completely ignored by the user agent. As far as the browser and indeed the website’s end user are concerned, this data does not exist.

Every HTML element may have any number of custom data attributes specified, with any value.

Data attributes can be used in the following scenarios -

  • To store the initial height or opacity of an element which might be required in later JavaScript animation calculations
  • To store parameters for a Flash movie that’s loaded via JavaScript
  • To store custom web analytics tagging data 
  • To store data about the health, ammo, or lives of an element in a JavaScript game
  • To power accessible JavaScript <video> subtitles

A data attribute like this  data-page-num="42" can be accessed using the jQuery data() method -

console.log($('section').data('pageNum');

jQuery lets you grab values of CSS settings for a class/ID/element -
$('.main').css("z-index");

So though it may be wild & unsuitable to do, you can store metadata in CSS too (as a hack in HTML5 unsupported browsers) & extract those values with jQuery.

Also see:
HOW TO link directly to a certain part of a web page that you don't own



Comments