You are reading a page on Ben Weaver's Website.

HTML5 dataset jQuery plugin

2009.09.09 Read More code jquery javascript

The HTML5 specification allows any DOM element to have custom data attributes. These attributes are prefixed with data- and may be conveniently accessed through an element's dataset property. The jquery.dataset plugin provides similar functionality.

So what is this good for? The HTML5 specification indicates that custom attributes are private. Only the site should pay attention to them. This means they don't enhance the semantic quality of a document unless the reader has special, site-specific knowledge.

A good application of custom attributes is scripting. The Dojo Toolkit, for example, uses non-standard properties such as DojoType to support javascript widget initialization without requiring custom initialization scripts. Using HTML5, it's possible to create a similar type of general purpose widget/markup interface that remains standard-compliant.

The role attribute (see ARIA) could be a good choice to indicate the type of widget since it also enhances accessibility. Widget options could be gathered from $(element).dataset() or $.evalJSON($(element).dataset('options')). Using JSON in an attribute is ugly, but it would be straightforward to create complex options (lists, nested objects, etc).

A related project is the jQuery metadata plugin. It provides a way to retrieve additional data embedded in an element's class attribute, non-standard attributes, nested script tags, or HTML5 custom attributes. The jquery.dataset plugin is simple, focused, and allows HTML5 custom attributes to be retrieved and manipulated.