jQuery Edge: Enhanced .toggleClass()
1 min read
In jQuery 1.3.3 1.4 the .toggleClass()
method will have a couple more modes of operation. Currently in jQuery 1.3.2 the .toggleClass()
method can only toggle one class name at a time. The new .toggleClass()
method will be able to toggle multiple class names and will also be able to toggle all the classes on or off. Here are the different ways you’ll be able to use .toggleClass()
.
// With the following element
// <div class="a b c"></div>
// Toggle all classes
$('div').toggleClass(); // <div class="" />
$('div').toggleClass(); // <div class="a b c" />
$('div').toggleClass( false ); // <div class="" />
$('div').toggleClass( true ); // <div class="a b c" />
// Toggle multiple classes
$('div').toggleClass( "a b" ); // <div class="c" />
$('div').toggleClass( "a c" ); // <div class="a" />
$('div').toggleClass( "a b c", false ); // <div class="" />
$('div').toggleClass( "a b c", true ); // <div class="a b c" />
By calling .toggleClass()
without passing any class names, it will toggle all the current classes on the element. To toggle multiple class names, just separate the class names with a space. The optional boolean can force the removal (false
) or force the addition (true
) of the class names.