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
?
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
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