jQuery add or remove class with toggleClass
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
Hi Jonathan,
I have a set of thumbnails that when the client hovers over each one it has a border that lights up and when they remove the mouse it is not lit. With this code they do not light up whenever I mouse over one and they do not light up when I remove the mouse from “one”. I tried the upper code but it wouldnt work for me.
Here is the code I implemented:
Eyveneena
18 Nov 09 at 6:52 am