jQuery Plugin: HTML5 Inline Data

HTML5 Data Attributes are sexy.

What’s sexier is an easy way to work with these data attributes using jQuery.

Sure, you could do something like:

jQuery('#pancakes').attr('data-type');

But who wants to type the “data-“ prefix over and over again?

So, here’s a quick little plugin I whipped up. It’s probably terrible when it comes to jQuery plugin standards (I do WordPress plugins, not jQuery), but it works. It works as a getter and setter.

Bonus: If you’re using jQuery 1.4.1+, the plugin supports well-formed JSON objects as data attribute values.


/*
* Inline Data - get and set HTML5 data attributes! Yay!
*
* Copyright (c) 2010 Mohammad Jangda (http://digitalize.ca), Vortex Mobile (http://www.vortexmobile.ca)
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
*/

(function($) {
    $.fn.inlinedata = function(name, value) {
        
        var prefix = 'data-';
        var attr = prefix + name;
        var values = []
        
        this.each(function(i) {
            var attrValue;
            
            // Setting values
            if(value) {
                // If an array is passed, the array index should correspond to the collection index
                if($.isArray(value)) {
                    // Check, check, check the index. Because out of bounds exceptions are the devil!
                    if(typeof(value[i]) !== 'undefined')
                        attrValue = value[i];
                    else
                        attrValue = '';
                } else {
                    // Not an array, so we're just giving all the elements the same value
                    attrValue = value;
                }
                this.setAttribute(attr, attrValue);
            } else {
                // Getting values
                attrValue = this.getAttribute(attr);
                
                try {
                    // try parsing as JSON
                    attrValue = jQuery.parseJSON(attrValue);
                } catch(e) { }
            }
            attrValue = (attrValue) ? attrValue : '';
            values.push(attrValue);
        });
        
        if(values.length == 1)
            return values[0]
        
        return values;
    }
})(jQuery);

Usage is simple: