Reputation: 35557
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.
Upvotes: 1
Views: 3516
Reputation: 630429
You can do it using .not()
to filter out the current element then .toggleClass()
, like this:
$("ul.menu li a").click(function() {
$("ul.menu li a").not(this).removeClass("currentMenu");
$(this).toggleClass("currentMenu");
});
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.
Upvotes: 3
Reputation: 18350
Something like this might work:
$("ul.menu li a").click(function() {
if ($(this).is(".currentMenu")) {
$(this).removeClass("currentMenu");
} else {
$(this).addClass("currentMenu");
}
$("ul.menu li a").not(this).removeClass("currentMenu");
});
Upvotes: 0