+ 4

How to toggle between 3 or more classes using JQuery?

Okay, so the code I'm currently working on requires an element to have differing classes, based on user input. I need to toggle between three classes when a button is clicked. Is it possible to place the classNames in a list, then iterate between each item in the list? And what about toggling between more than 3 classes? I've tried: $(function() { $("button").click(function(){ $("p").toggleClass("class1", "class2", "class3"); }); }); It doesn't work. Any help would be appreciated. 🙏

14th Jul 2017, 4:23 PM
Leigh E. O.
Leigh E. O. - avatar
4 Réponses
+ 7
I've missunderstood what you expect ^^ These changes should solve your problem: $(function(){ var class_index = 0; var class_list = ["class1", "class2", "class3", "class4"]; $("#one").click(function(){ var i = class_list.length; // while (i--) { $(this).toggleClass(class_list[class_index++],class_list[class_index]); class_index %= class_list.length; $(this).toggleClass(class_list[class_index]); // } }); });
14th Jul 2017, 7:02 PM
visph
visph - avatar
+ 7
@Visph, tinkering with your suggestion, the problem is solved. Here's the completed code: https://code.sololearn.com/WD6SYZBrt6Af/?ref=app The ToggleClass is in line 20 in the JS code. Thank you! 🙌
15th Jul 2017, 9:08 AM
Leigh E. O.
Leigh E. O. - avatar
+ 6
Something like that: $(function() { $("button").click(function(){ var c = ["class1", "class2", "class3"]; var i = c.length; while (i--) { $("p").toggleClass(c[i]); } }); }); ... and obviously you can adapt it to be use as a custom function: function toggleClassList(jqe,clist) { var i = c.length; while (i--) { jqe.toggleClass(c[i]); } } ... use: toggleClassList($("p"),["class1", "class2", "class3"]);
14th Jul 2017, 5:03 PM
visph
visph - avatar
+ 2
@visph, tried your suggestion. Doesn't work... only toggles between the first & the last class in the list... https://code.sololearn.com/WTx9fILkWm6u/?ref=app
14th Jul 2017, 6:33 PM
Leigh E. O.
Leigh E. O. - avatar