Tutorial :Toggling between Menu Active states using jQuery


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.

Hope this makes sense.


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.


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");  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »