0

I'm trying to configure jQuery plugins trough classes applied to elements to which these plugins are attached.

for example:

<div class="move amt-10 dir-left">
...
</div>

and the js:

$('.move').each(function(){
  var classes = $(this).attr('class');

  // this is from: http://stackoverflow.com/questions/3955345/javascript-jquery-get-number-from-string
  var amount = parseInt(/amt-(\d+)/.exec(classes)[1], 10);
  var direction = /dir-([^\s]+)/.exec(classes)[1];
  // do stuff here based on amount/direction variables
});

it works for this particular case, but since I'm doing this for other plugins too, I was wondering how could create some kind of "parser" for this kind of options passed trough classes, so I can write less code :)

Alex
  • 66,732
  • 177
  • 439
  • 641
  • 1
    Does this have to work with existing third-party code so you're forced to use class attribute? Because it looks like you are abusing classes to implement `data`: http://api.jquery.com/data/ – pawel Apr 26 '11 at 15:30
  • no, I just like the fact that you can control a plugin from the html. is this a bad idea? – Alex Apr 26 '11 at 16:26
  • Using `jQuery.data` you have access to HTML5 `data-` attributes, look at the examples provided in docs linked above. In your use case it could be `
    `//posted as an answer below
    – pawel Apr 26 '11 at 16:55

2 Answers2

1

Your example refactored using jQuery.data and HTML5 data-* attributes

<div class="move" data-amt="10" data-dir="left"></div>

$('.move').each(function(){
  var amount = $(this).data('amt');
  var direction = $(this).data('dir');
  // do stuff here based on amount/direction variables
});
pawel
  • 35,827
  • 7
  • 56
  • 53
  • yeah, that's the point of using jQuery :) you should test it yourself, but I see no reason why a cross-browser framework feature wouldn't work in all browsers. – pawel Apr 26 '11 at 17:10
1

Another good option for this sort of thing is the jquery metadata plugin:

http://plugins.jquery.com/project/metadata

ScottE
  • 21,530
  • 18
  • 94
  • 131