toggleClass
is great if I just have two presentations styles I want to use, but a lot of times I've got more than two states that I want to use.
For example, if I want to rotate through three classes:
if ($(this).hasClass("A"))
$(this).removeClass("A").addClass("B");
else if ($(this).hasClass("B"))
$(this).removeClass("B").addClass("C");
else if ($(this).hasClass("C"))
$(this).removeClass("C").addClass("A");
I'd like to have a simple method that did this for me, something like:
$(this).rotateClass('A', 'B', 'C');
Is there an existing jQuery method or plugin that does this?
Put them in an Array:
Then in the handler:
The use of
this.className
assumes that there's not other classes applied to this element.JSFIDDLE DEMO
If there may be other classes, use this:
JSFIDDLE DEMO
If there may be other elements, and each need their own state, you could use a closure to associate a unique
i
with each element:JSFIDDLE DEMO
My current solution:
This plugin code will rotate between the passed classes (however many there are (2-n). If none of the passed classes are found on the object, then the first class is set.
This version of the code assumes that you are applying the same classes to all the DOM objects in the jQuery object and they all have the same state. It could be extended to treat each DOM object in the jQuery object separately and rotate each ones separately if that was required.
You can still use
toggleClass
and pass it a function instead:Not the easiest code to maintain though, so it would probably be better to wrap it in a plugin.
http://jsbin.com/inaduy/edit#javascript,html,live
And now made in to a very basic plugin (that needs a bit of validation). You just pass an array of objects containing pairs of classes to swap.
http://jsbin.com/inaduy/2/edit
Here's my attempt at it.
You would use it by calling
.rotate
on the element and passing in an array of classes to rotate.Here's an interactive demo. I just added the animate to show that you can apply other jQuery functions to the element after the rotate is finished.
The reason we use the modulus operator is, if i > the length of the array then we want the correct index. E.g array of classes is ['A','B','C'], if the current class on our element is 'C' then the index of the current class is 2 (arrays are 0 index based), then if we increment 2 + 1 = 3 to get the class we want to rotate it to but we don't have any class at index 3 hence 3 % 3 = 0 which is the index of 'A', that's what we want, hence the modulus will get us the correct index every time.
Here's what I use:
No for loops, no hasClass calls, compatible with sets of elements, very compact and very performant.
Usage: