Search code examples
jquerytoggletoggleclass

Turning off toggleClass when any other link clicked?


I have this toggle sliding open a menu and adding an active class to let you know its open, i've cobbled this together and there is a glitch..

$(".parents-toggle > a").click(function () {
          $(this).toggleClass('active');
         $(".parents-toggle > ul.sub-menu").not($(this).siblings()).slideUp();
         $(this).siblings(".sub-menu").slideToggle();
      });

      $(".parents-toggle-inner > a").click(function () {
      $(this).toggleClass('active');
         $(".parents-toggle-inner > ul.sub-menu").not($(this).siblings()).slideUp();
         $(this).siblings(".sub-menu").slideToggle();
      });​

It stays active if you click any other button as well, so staying active unless you close it....

Is it possible to remove the active class if you click any other link on the page? So even if there is a another toggle menu separate to this one, so any link ideally..?

http://jsfiddle.net/24k5U/2/

As you can see you get a mass of orange/active buttons

Any help would be amazing.


Solution

  • Add a $('.active').removeClass('active'); in the click event. That should fix it.

    That way, you code now becomes:

    $(".parents-toggle > a").click(function () {
        $('.active').removeClass('active');  // <---- This line added
        $(this).toggleClass('active');
        $(".parents-toggle > ul.sub-menu").not($(this).siblings()).slideUp();
        $(this).siblings(".sub-menu").slideToggle();
    });
    

    Basically, what you are doing is making sure that there are no links with class=active before you toggleClass() the clicked link.

    You can do the same thing to inner or sub links.