Expected: I would like each tim...">

What is the correct way to switch switchClass in jQuery?

Consider:

<div id="obj" class="foo"><!-- --></div> 


Expected:

I would like each time to press keys to switch between the classes "foo" and "bar". The Toggle class simply adds and removes the "bar", which is not enough.

I can fulfill the effect that I want to use using a combination of .hasClass() , a triple condition and switchClass , but I would like to see how others did it. I am trying to increase my experience using jQuery.

This may be what I want, but I'm also trying to reduce external plugins.

+4
source share
1 answer

If I get you right, you can just use .toggleClass() .

 $('#obj').click(function() { $(this).toggleClass('foo bar'); }); 

Ref . : . toggleClass ()

Example: http://www.jsfiddle.net/sTBcb/

+9
source

All Articles