addClass/removeClass are not working properly

508 views Asked by At

I have 5 button each of them have the class .leg, I want when the user clicks on one of them to add 'active' on the class attribute and remove it from every other, so I have:

j$(".leg").on "click", (event)->
  j$('.leg').removeClass('active')
  j$(event.target).addClass('active')

Sometimes when I click on one of the button the 'active' class is not added. I suspect that the removeClass has not finish its execution, 'active' is added and then removed again. Since the removeClass does not have a callback is there any other way to fix this issue?

http://jsfiddle.net/k4605e3z/

3

There are 3 answers

1
Ionică Bizău On BEST ANSWER

Use $(this) instead of $(e.target):

$('.leg').click(function(event){
  $('.leg').removeClass('active');
  $(this).addClass('active');
});

this is the dom element selected when you added the click handler.

JSFIDDLE

0
Mathieu Labrie Parent On

Simply change this :

$('.leg').click(function(event){
    $('.leg').removeClass('active');
    $(this).addClass('active');
});
0
anpsmn On

You have an element inside .leg so when you click, the target is the span. You can get the parent by this event.target.parentElement

$('.leg').click(function(event){
  $('.leg').removeClass('active');
  $(event.target.parentElement).addClass('active')
})

Fiddle