Joe Joe - 1 year ago 112
jQuery Question

jquery: changing class (but not) changing action

I found a strange behaviour.. surely is know but I do not know how to fix it.

I have a button that has to do 2 different actions depending on the current class.

When clicked, it toggles its class, in this way, at next click will make a different action..
but it continues to perform the "old" action, like class has not been changed

To be more clear...

here the relative Fiddle

you can see that when you click button
it writes
and the two buttons toggle their class (since colors has changed): therefore it seems all OK

But if you click again button
instead of writing
that is what should happen when
class b
button is pressed, it again writes

Clearly can have 2 buttons for the 2 action and toggle the 2 buttons instead of exchanging the class, but I would like to understand if I'm doing something wrong or the reason of this strange behaviour.


Answer Source

You need to use event delegation as you are adding and removing classes which are used for binding events:


Working Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download