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 ...
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With