jQuery Edge: Enhanced .toggleClass()
Wednesday, May 6, 2009
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.
Posted in jQuery, jQuery Edge with 3 comments
I think this will come in handy–looking forward to 1.3.3.
(btw, is there a typo in the second example for “Toggle multiple classes? Shouldn’t the result be
// <div class="b" />?)By Mike T. on Wednesday, May 6, 2009 at 02:49 PM
@Mike,
Actually, the example is correct ( if not confusing :). The element starts off with “a b c” and then I toggle off “a b”. Next I toggle on “a” and toggle off “c”. The “b” class was not toggled back on until the last statement.
Hope that clear things up and hopefully illustrates the difference between toggling the whole class vs multiple (or single) classes.
By Brandon Aaron on Wednesday, May 6, 2009 at 03:01 PM
You know, I was thinking about this example last night at the grocery store and then a light bulb went on. :)
Thanks for the follow-up explanation, though.
By Mike T. on Thursday, May 7, 2009 at 08:12 PM