The 'toggleClass' function will add or remove a single class.
So $('.item').toggleClass('itemcontent')
will either add or remove the 'itemcontent' class to all of the elements with a class of item
. If you call toggleClass('itemcontent')
many times, you'll remove the class itemcontent
, then add the class, then remove it, and so on.
If you need to toggle between two classes, you need to send two classes to the toggleClass
call.
Like this:
$('.item').toggleClass('class1 class2')
This would toggle between class1
and class2
assuming that the element stated with one and not the other.
So if you want class item
to toggle between class1
and class2
your code should be:
$( ".item" ).click(function() {
$(this).toggleClass('class1 class2');
});
Remember that elements can have multiple classes at the same time. To start, your item
should have either class1
or class2
. Then, the item
will toggle between the two classes. If you item
has neither class1
nor class2
to start, it will just turn on and off both classes at the same time.