tags:

views:

20

answers:

2

Hi,

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 jQyery 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.

Hope this makes sense.

Thanks.

A: 

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");
});
Jamie Wong
+2  A: 

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.

Nick Craver
Perfect Nick - thanks.
tonsils