Codecraker
Codecraker

Reputation: 337

Active class not working properly

I have some menu items and in the menu I have a plus(+) sign. When I click on the plus sign it should add a class and look like cross. It is happening but when I click the cross sign it does not removing the sign so that I can get the plus sign again.

$(document).ready(function(){    
  $('.nav-link').click(function(){
    $('.nav-link').removeClass('addplus');
    $(this).addClass('addplus');
  });

});

Here is the Example.

Upvotes: 1

Views: 502

Answers (4)

Michael Tamm
Michael Tamm

Reputation: 943

You always add the class addplus in the last line of your click handler. Try the following instead:

$(document).ready(function(){    
  $('.nav-link').click(function(){
    if ($(this).hasClass('addplus')) {
      $(this).removeClass('addplus');
    } else {
      $(this).addClass('addplus');
    }
  });
});

Upvotes: 0

David Wilkinson
David Wilkinson

Reputation: 5118

I've gone a bit around about the houses here, but this works using parent and siblings:

$('.nav-link').click(function() {
    $(this).parent(".nav-item").siblings().children(".nav-link").removeClass('addplus');
    $(this).toggleClass('addplus');
});

I wouldn't do a blanket removeClass across all matching elements like you've done, I'd pick them out by excluding the currently matched element. Revised fiddle: https://jsfiddle.net/epqxb6L7/5/

Upvotes: 1

Himan
Himan

Reputation: 379

It's because your code is removing and adding the same class every time click event triggers. Try something like this

$(document).ready(function(){    
   $('.nav-link').click(function(){
   $(this).toggleClass('addplus'); //THIS WILL ADD/REMOVE CLASS ALTERNATIVELY
  });
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337713

The issue is because you are always removing, then immediately adding the class back on the clicked element. To fix this exclude the current element from the removeClass() call using not(), then use toggleClass() to add/remove the class to the required element, like this:

$('.nav-link').click(function() {
  $('.nav-link').not(this).removeClass('addplus');
  $(this).toggleClass('addplus');
});

Updated fiddle

Upvotes: 4

Related Questions