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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This always happens.. It's something simple and I just couldn't wrap my finger around it. Thanks.
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

1 Comment

The reason stems from my desire to use this format: 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: pastebin.com/6DxTvgzL especially if the names are long and there are multiple options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.