Html 5 data-attributes into jquery plugin options format

Go To StackoverFlow.com

0

In addition to jquery plugin options, I want to override those values with html5 data-attributes.


This is the desired format for the optionis:

var defaults = {
   text: {
      color: 'red',
      opacity: 0.5
   },
   button: {
      width: 100,
      height: 30
   }
}

I wanted to format the data-attribute something like this:

<div data-text="color:'red', opacity: 0.5"></div>

...But you wouldn't be able to read this data o.text.color because it simply does not exist. There is however data inside o.text.

How could I format the data-attribute so that I can fetch the value with o.text.color?

2012-04-05 18:39
by Joonas


2

Just pass an object formatted like a json string to the attribute, and jQuery data will parse it for you.

<div class="test" data-test='{ "test1":"Lorem","test2":"Ipsum" }'></div>

Also see updated fiddle

2012-04-05 18:46
by Razor
This always happens.. It's something simple and I just couldn't wrap my finger around it. Thanks - Joonas 2012-04-05 18:56


0

This isnt very clean and reminds me of onclick events in HTML. Why not seperate them out into data-test1="Lorem" & data-test2="Ipsum"?

Plugin could be something like this (extending jquery plugin boilerplate):

function Plugin( element, options, objD ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options, objD );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
}

$.fn[pluginName] = function ( options ) {
  return this.each(function () {
    if (!$.data(this, "plugin_" + pluginName)) {
        var objD = $(this).data();
        $.data(this, "plugin_" + pluginName, new Plugin( this, options, objD ));
    }
  });
};

Im no guru but works well for me

2013-01-28 10:26
by Adi
The reason stems from my desire to use this format: http://pastebin.com/pnEeNje7 for the options, because I find it to be a bit cleaner and easier to remember compared to the usual way of laying them out like this: http://pastebin.com/6DxTvgzL especially if the names are long and there are multiple options - Joonas 2013-01-28 11:13
Ads