HTML5 Data attributes and jQuery’s .data – pairing made in heaven

May 12, 2010 in jQuery Plugins

UPDATE
jQuery 1.4.3+ now does this in core.
No need for this plugin!


I really like the idea of the data-* properties in the spec for HTML5, unfortunately they’re not supported directly by any browser it seems yet; even jQuery 1.4.2 doesn’t really support them (due to the non-browser support I guess).

Anyway, I really wanted to make use of them in an application I’ve been using and after reading John Resig’s (@jresig) post on the subject (http://ejohn.org/blog/html-5-data-attributes/) I set about adding a little snippet to extend jQuery’s .data so that it would support these parameters. So here is the small plugin that will extend the data function in jQuery to enable access to this functionality.

Enjoy

(function($){
    $.fn.extend({
        '_data': $.fn.data,
        'data' : function( key, value ) {
            if ( typeof key === "undefined" && this.length ) {
                return jQuery.data( this[0] );
            } else if ( typeof key === "object" ) {
                return this.each(function() {
                    jQuery.data( this, key );
                });
            }
            var retValue;
            retValue = $.fn._data(key, value);
            if ('undefined' == (typeof retValue) || retValue.length == 0) {
                var nakedElem = this.get(0);
                if (nakedElem.hasOwnProperty('dataset')) {
                    if ('undefined' != (typeof nakedElem.dataset[key])) {
                        retValue = nakedElem.dataset[key];
                    }
                } else {
                    retValue = this.attr('data-'+key);
                }
            }
            return retValue;
        }
    });
})(jQuery);

All comments are gratefully received :)