1

I have built my own custom jQuery plugin and I'm trying to override the default options using HTML data attributes. I have added a prefix (pager) to each one so my final mark-up is:

<div class="pager" data-pager-page="1"></div>

Now say I have an object:

var options = { page: 0 };

I'd like to override the options by saying something like:

var o = $.extend({}, options, $('.pager').data('pager'));

However this doesn't work. After doing abit of debugging I discovered $('.pager').data('pager') was returning undefined. If I say:

$('.pager').data();

This returns the following object:

{ pagerPage: 1 }

I guess I would need some way to convert this object to the one I need. Please note that I would like to add many options and code should handle this without me having to handle each individual option.

I'm sure others have run into this problem and I'd appreciate any help. Thanks

nfplee
  • 7,643
  • 12
  • 63
  • 124
  • 1
    I would suggest just having a collection of possible data attributes, then iterating over them to see which ones are defined and handle them accordingly. Look at how jQuery Cycle2 does it, malsup may have come up with some other intuitive way of handling it. – Kevin B Feb 12 '13 at 22:52
  • Thanks, their website seems down at the moment though. – nfplee Feb 12 '13 at 23:02
  • github is still up though, https://github.com/malsup/cycle2 – Kevin B Feb 12 '13 at 23:03
  • 1
    And here's what you're looking for: https://github.com/malsup/cycle2/blob/master/jquery.cycle2.core.js#L40 – Kevin B Feb 12 '13 at 23:04
  • Nice one thanks, I'll see if I can dig out what I need. – nfplee Feb 12 '13 at 23:05

2 Answers2

1

Incase anyone is interested the following code did the trick:

var data = $('.pager').data();

for (var p in data) {
    if (data.hasOwnProperty(p) && /^pager[A-Z]+/.test(p)) {
        var shortName = p[5].toLowerCase() + p.substr(6);
        data[shortName] = data[p];
    }
}

var o = $.extend({}, options, data);

Note: Replace 5 with the length of the prefix and 6 with the length + 1. Hope this helps.

Thanks Kevin for pointing me in the right direction.

nfplee
  • 7,643
  • 12
  • 63
  • 124
  • Thanks for this one. I was searching the web for a solution but eventually this seems to be the only one. Would be great if jQuery supported data attribute prefixes. – Robin van Baalen Feb 05 '14 at 19:12
0
<div id="test" data-key="xyz">helloooooo</div>

<script type="text/javascript">
var value = $("#test").data("key");
alert(value); //This will show you "xyz"
</script>

i think it is in HTML4 and HTML5 true;

farshad
  • 1
  • 1