.removeClass not working, how does addClass do?

Forgive me for being a noob, but shouldn't this work?

$(document).ready(function() { $('.button').click(function() { $(this).addClass('button-clicked'); }); $('.button-clicked').click(function() { $(this).removeClass('button-clicked'); }); }); 

Should a second click remove the class and return it to .button?

Here it is on jsfiddle: http://jsfiddle.net/pXdwM/

+4
source share
2 answers

no, because at the moment you call the second click() , the button does not have a ".button-clicked", and therefore an event handler is not assigned. You can rewrite it like this:

 $('.button').click(function() { $(this).toggleClass('button-clicked'); }); 

or use live()

 $('.button-clicked').live("click", function() { $(this).removeClass('button-clicked'); }); 
+9
source

You add an event to each element with a ".button-clicked" class, but the class does not apply until you actually click. So you need to move the second listener to the first callback or use the toggleClass function:

 $('.button').click(function() { $(this).toggleClass('button-clicked'); }); 
+2
source

All Articles