$.html5data

You wrote an awesome jQuery plugin. You're already $.extending like a boss.
Now make any setting available to your plugin users via HTML5 data attributes.

Turn this:

<section
data-myplugin-foo-bar="true"
data-myplugin-offset-x="10"
data-myplugin-offset-y="20">
</section>

Into this:

{
    //note the lack of the 'myplugin' prefix
    fooBar: true,
    offsetX: 10,
    offsetY: 20
}

So you can do this:

var settings = $.extend(
        {}, //new object
        defaults,
        options,
        $elem.html5data('myplugin')
    );

Don't want a dependancy?

var settings = $.extend(
        {},
        defaults,
        options,

        //check if the plugin exists first
        ( typeof $.html5data === 'function' ?
          $elem.html5data('myplugin')
          //if not, fall back to the global namespace
          : $elem.data() )
    );

Customise $.html5data

All settings are completely optional.

$elem.html5data('myplugin', {
	
    //boolean settings
    parseBooleans: true|false [default: true],
    parseNulls: true|false [default: true],
    parseNumbers: true|false [default: true],

    //custom parsing function
    parse: function(val){ return val; }

});

Why would you want this?

Because it makes your plugin even more awesome.

Oh, you wanted more detail?

jQuery's data method, when called without a parameter (as of v1.4.3), converts the HTML5 data attributes and all values set against an element using $.data into a single hash that you can $.extend with your plugin's default settings.

There are a couple of problems when using this approach with HTML5 data:

The purpose $.html5data is to:

As a bonus, $.html5data parses JSON, booleans, nulls and numbers by default.

Unlike $.data, each of these parsing options can be optionally disabled. You can even create your own custom parsing function.

Using $.html5data in your project?

I'd love to hear about it! Let me know on Twitter or GitHub— and, of course, if you have any improvements, send me a pull request!

Fork me on GitHub