jQuery Minute™

…a jQuery Minute™ later and you're done!



jQuery add or remove class with toggleClass

without comments

Back in May of 2008 I posted about how to dynamically call a jQuery function and the practical use in adding or removing a class in one fell swoop. Since that post the toggleClass method has been updated to accept a second argument, a boolean value to signify adding or removing a class.

First the classic toggle class example:

1
$('body').toggleClass('blue');

Which just as the method describes will add the class “blue” if it doesn’t exit or remove it if it does.

In the next example we make use of addClass or removeClass

1
2
3
4
5
if ( $('body').hasClass('makeBlue') ) {
    $('body').removeClass('blue');
} else {
    $('body').addClass('blue');
}

Which has the same result and function as our first example with the difference that we’re adding or removing a class based upon the condition of body having the class “makeBlue”.

So here is an updated example making use of toggleClass along with the second argument that when true adds the class and conversely if false removes the class.

1
2
var addBlue = $('body').hasClass('makeBlue');
$('body').toggleClass('blue', addBlue );

And the final reduced version:

1
$('body').toggleClass('blue', $('body').hasClass('makeBlue') );

Cheers,
- Jonathan

Written by jdsharp

October 3rd, 2009 at 12:13 am

Leave a Reply