Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to toggle a switchClass in jQuery?

Consider:

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


Expected:

What I'd like is to keep switching between class "foo" and "bar" on each mouse click. Toggle class just seems to add and remove "bar", which isn't good enough.

I can accomplish the effect I want with using a combination of .hasClass(), a ternary condition, and switchClass, but I'd like to see how others would accomplish this - I'm trying to increase my experience with jQuery.

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

like image 587
vol7ron Avatar asked Dec 29 '22 05:12

vol7ron


1 Answers

If I get you right, you might just want to use .toggleClass().

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

Ref.: .toggleClass()

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

like image 85
jAndy Avatar answered Feb 15 '23 07:02

jAndy