Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse $.extend configuration from data attribute

I know I can use $.data but how can I iterate trough all data- attributes and merge the values with the default plugin configuration?

(function($){

  $.fn.plugin = function(opts){  

    opts = $.extend({
      foo: 'abc',
      boo: 45
    }, opts);

    return this.each(function(){        
          ...
    });

  };
})(jQuery);

So if I use

$('.el').plugin();

it should look for data attributes on .el, like data-foo etc ...

like image 840
Alex Avatar asked Jan 31 '12 19:01

Alex


3 Answers

In your each() loop, you can merge the object returned by data() with your defaults, then merge the opts argument with the result in a single call to $.extend():

$.fn.plugin = function(opts) {
    return this.each(function() {        
        var thisOpts = $.extend({
            foo: "abc",
            boo: 45
        }, $(this).data(), opts);
        // Now use 'thisOpts' as operating parameters for this element...
    });
};

This should achieve what you want: the opts argument has the highest priority, followed by the data- attributes of the current element, followed by the plugin defaults.

like image 51
Frédéric Hamidi Avatar answered Sep 22 '22 19:09

Frédéric Hamidi


The .data() method supports data- attributes.

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

Calling it without speciying a parameter will return an object with key/values pairs for all the data attributes:

var mydata = $("#mydiv").data();
like image 42
Didier Ghys Avatar answered Sep 18 '22 19:09

Didier Ghys


You can get all the attributes for an element like this:

//get the element and setup an array for output
var el  = document.getElementById("o"),
    arr = [];

//loop through each attribute for the element
for (var i = 0, attrs = el.attributes, l=attrs.length; i < l; i++){

    //if the current attribute starts with `data-` then add it to the array
    if (attrs.item(i).nodeName.substr(0, 5) == 'data-') {
        arr.push(attrs.item(i).nodeName);
    }
}

Here is a demo: http://jsfiddle.net/ksbD3/1/

Also I got most of the above code from this answer: Get all Attributes from a HTML element with Javascript/jQuery

like image 3
Jasper Avatar answered Sep 22 '22 19:09

Jasper