A repository of over 1000 quality jQuery plugins

jQuery .toggleClass()

Learn all about the jQuery function .toggleClass().

This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to a simple <div>:

1
<div class="tumble">Some text.</div>

The first time we apply $( "div.tumble" ).toggleClass( "bounce" ), we get the following:

1
<div class="tumble bounce">Some text.</div>

The second time we apply $( "div.tumble" ).toggleClass( "bounce" ), the <div> class is returned to the single tumble value:

1
<div class="tumble">Some text.</div>

Applying .toggleClass( "bounce spin" ) to the same <div> alternates between <div class="tumble bounce spin"> and <div class="tumble">.

The second version of .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter’s value is true, then the class is added; if false, the class is removed. In essence, the statement:

1
$( "#foo" ).toggleClass( className, addOrRemove );

is equivalent to:

1
2
3
4
5
if ( addOrRemove ) {
$( "#foo" ).addClass( className );
} else {
$( "#foo" ).removeClass( className );
}

As of jQuery 1.4, if no arguments are passed to .toggleClass(), all class names on the element the first time .toggleClass() is called will be toggled. Also as of jQuery 1.4, the class name to be toggled can be determined by passing in a function.

1
2
3
4
5
6
7
$( "div.foo" ).toggleClass(function() {
if ( $( this ).parent().is( ".bar" ) ) {
return "happy";
} else {
return "sad";
}
});

This example will toggle the happy class for <div class="foo"> elements if their parent element has a class of bar; otherwise, it will toggle the sad class.