Last active
September 20, 2016 22:31
-
-
Save jerivas/366f7c7cf796fe52cd960e0b790d9136 to your computer and use it in GitHub Desktop.
Cycle through CSS classes (including no class at all)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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