Skip to content

Instantly share code, notes, and snippets.

@rafaelrinaldi
Created February 14, 2014 20:30
Show Gist options
  • Select an option

  • Save rafaelrinaldi/9008634 to your computer and use it in GitHub Desktop.

Select an option

Save rafaelrinaldi/9008634 to your computer and use it in GitHub Desktop.
/**
* Simple jQuery plugin to iterate through a list of values.
*
* Markup:
*
* <a data-iterate='foo,bar,baz'>Click to iterate</a>
*
* Usage:
*
* $('a').iterate(); // bar
* $('a').iterate(); // baz
* $('a').iterate(); // foo
*/
(function($) {
/**
* @return {String} Next item on the iterations list.
*/
$.fn.iterate = function() {
var data = this.data(),
values = data.iterate.split(','),
iterations = values.length - 1,
index = parseInt(data.iterationIndex, 10) || 0;
if(index === iterations) {
index = 0;
} else {
++index;
}
// Saving current iteration index on the element data attributes.
this.data({iterationIndex: index});
return values[index];
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment