Arron
Arron

Reputation: 916

jQuery on() doesn't work when switching classes

[edit] THIS CODE DOES WORK

Found out had multiple on() handlers on the same event/class. [/edit]

I'm using the following code:

$selector.on('click', '.heya', function($e){
     alert('heya');
     jQuery(this).attr('class', 'byebye');
});


$selector.on('click', '.byebye', function($e){
     alert('byebye');
     jQuery(this).attr('class', 'heya');
});

Now clicking one of the elements once works correctly, but when clicking it again both callbacks are called. Somehow the previous "on()" trigger did not get removed. Anyone knows why? I know I can solve this issue differently, but this would be the cleanest solution...

Upvotes: 0

Views: 69

Answers (3)

Vikram
Vikram

Reputation: 713

Try this code:

$(".heya,.byebye").on('click', function($e){

     $(this).toggleClass('byebye heya');

});

JSFiddle

Upvotes: -1

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

Try this this will help you to solve your problem.

$(".heya").on('click', function($e){
     alert('heya');
     $(this).attr('class', 'byebye');
});


$(".byebye").on('click', function($e){
     alert('byebye');
     $(this).attr('class', 'heya');
});

Upvotes: 0

Michal Klouda
Michal Klouda

Reputation: 14521

Use addClass and removeClass methods instead.

$selector.on('click', '.heya', function($e){
     alert('heya');
     $(this).removeClass("heya").addClass("byebye");
});

$selector.on('click', '.byebye', function($e){
     alert('byebye');
     $(this).removeClass("byebye").addClass("heya");
});

Upvotes: 2

Related Questions