+ 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. 🙏
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]);
// }
});
});
+ 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! 🙌
+ 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"]);
+ 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