Skip to content

Instantly share code, notes, and snippets.

@jerivas
Last active September 20, 2016 22:31
Show Gist options
  • Save jerivas/366f7c7cf796fe52cd960e0b790d9136 to your computer and use it in GitHub Desktop.
Save jerivas/366f7c7cf796fe52cd960e0b790d9136 to your computer and use it in GitHub Desktop.
Cycle through CSS classes (including no class at all)
var classes = ["style1", "style2"];
$("element").on("click", function(event) {
// Don't execute if the event is bubbling from a child node
if (event.target !== this) return;
var $el = $(this);
$.each(classes, function(i, klass) {
if ($el.hasClass(klass)) {
$el.removeClass(klass)
// Add the next class (if any)
if (i < classes.length - 1) $el.addClass(classes[i + 1]);
// Break the each loop after matching
return false;
}
// If no class matched, add the first one
if (i === classes.length - 1) $el.addClass(classes[0]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment