user4630
user4630

Reputation: 633

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.

Upvotes: 0

Views: 1938

Answers (2)

Abhilash
Abhilash

Reputation: 1610

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.

Upvotes: 1

user1726343
user1726343

Reputation:

Remove the class from other elements at the same level before you apply it to any others:

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

Upvotes: 0

Related Questions