Reputation: 12512
I need to be able to toggle class when I click an element. It works fine for that element:
$(".main").click(function() {
$(this).toggleClass("classA").toggleClass("classB");
});
But I would like to add to it to toggle classes for all elements on the page that have a particular class, say "togToo". For those elements I need to toggle between "classC" and "classD".
I'm almost certain there's a way to combine that into one click...
^^^ UPDATED ABOVE ^^^
Upvotes: 36
Views: 74471
Reputation: 41
I know it's an old question, but since jQuery v3.3, we can use an array of classes like this:
$('.main').click(function() {
$(this).toggleClass(['classA','classB']);
$('.togToo').toggleClass(['classC','classD']);
});
Reference: http://api.jquery.com/toggleclass/#toggleClass-classNames
Upvotes: 1
Reputation: 31
I do it this way, having multiple images with class $('.img-polaroid') and class $('.drag'), when one of the images is clicked, it remove the $('.drag') to this element after having add it back to all of them
$('.img-polaroid').click(function(){
if ($(this).hasClass('drag')) {
$('.img-polaroid').addClass('drag');
$(this).removeClass('drag');
}
});
Upvotes: 0
Reputation: 805
You can toggle N classes all at once
$(/* selector */).toggleClass('classA classB classC');
Upvotes: 14
Reputation: 2977
You can simply do something like
$(".classC").toggleClass("ClassD");
inside the "click" handler
Upvotes: 0
Reputation: 4098
If you're looking for a way to toggle through mutliple classes one after each other and not all together I quickly wrote a little script you can use:
https://github.com/ThibaultJanBeyer/.toggleClasses-for-jQuery
it extends a new jQuery method .toggleClasses() that does exactly what you want. check it out and feel free to make it better if you have improvements :)
Upvotes: 0
Reputation: 146302
Answer Updated
$(".main").click(function() {
$(this).toggleClass("classA").toggleClass("classB");
$('.togToo').toggleClass("classC").toggleClass("classD");
})
Upvotes: 24
Reputation: 2342
This should do the trick:
$(".main").click(function() {
$(this).toggleClass("classA").toggleClass("classB");
$(".togToo").toggleClass("classC").toggleClass("classD");
));
Also, when toggling classes, i would suggest having a base class, and a toggle class, instead of toggling between two classes.
Upvotes: 2
Reputation: 23943
If the elements to be toggled start off with one of the two classes, you can then toggle back and forth like this:
$('#element_to_click').click( function(){
$('.togToo').toggleClass('classC classD');
});
Upvotes: 105
Reputation: 39491
Why won't you use jQuery class selector?
$('.togToo').toggleClass("classC").toggleClass("classD");
Upvotes: 3