I have the following jQuery code:
$("ul.menu li a").click(function() {
$("ul.menu li a").removeClass("currentMenu");
$(this).addClass("currentMenu");
});
At page startup, my “Home” menu button is set to “currentMenu”, which basically has a color background set to orange.
What I am trying to achieve, which the above jQuery code doesn’t cater for is if I click on the existing “Home” button that is set to “currentMenu”, I actually would like to remove this class, so the “Home” button no longer has the orange background color and vice-versa, when “Home” button unset, then set to “currentmenu” class.
You can do it using
.not()to filter out the current element then.toggleClass(), like this:You can test it out here, this just filters the clicked anchor out of the collection so it won’t be affected by the
.removeClass()then does.toggleClasss()instead of.addClass()to give the toggle on/off effect you’re after.