Search code examples
jqueryclassbuttonclick

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 A it writes AAA and the two buttons toggle their class (since colors has changed): therefore it seems all OK

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

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.

Regards


Solution

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

    $('body').on('click','.a',function(){
        $('#R').html('AAA');
        $('#A').addClass('b').removeClass('a');
        $('#B').addClass('a').removeClass('b');
    });
    $('body').on('click','.b',function(){
        $('#R').html('BBB');
        $('#B').addClass('b').removeClass('a');
        $('#A').addClass('a').removeClass('b');
    });
    

    Working Demo