psorensen
psorensen

Reputation: 827

jQuery - Nested list: collapse others when one opens

I'm trying to set up an accordion style menu where, in a nested list structure, clicking the anchor tag adds a class to the neighboring ul which changes it's height and thus makes it visible. I've successfully made it work, but I want to extend it to close other submenus when one is selected.

Here's my menu markup:

<nav>
  <ul id="menu" class="">
    <li class="dropdown">
      <a>Markets <b class="caret"></b></a>
      <ul class="submenu">
        <li>Menu Item</li>
        <li>Menu Item</li>
        <li>Menu Item</li>
      </ul>
    </li>
    <li class="dropdown">
      <a>Management Focus <b class="caret"></b></a>
      <ul class="submenu">
        <li>Menu Item</li>
        <li>Menu Item</li>
        <li>Menu Item</li>
      </ul>
    </li>
  </ul>
</nav>

Here is the jQuery:

  $('li.active ul').addClass('show');
  $('#menu-market-intelligence-bar>li.dropdown>a').click( function(e){
    $(this).parent().children('ul').toggleClass('show');

    ** // $(this).parent().parent().children('li > ul').not(this).removeClass('show');

    e.preventDefault();
  });

** This is my attempt to hop back up to the parent of the parent and grab it's children elements that are NOT the current element. Probably pretty ugly. Any help greatly appreciated!

Upvotes: 0

Views: 661

Answers (1)

Amin Jafari
Amin Jafari

Reputation: 7207

in my opinion the easiest way would be to remove the show class from all the uls except the sibling ul, and then toggle the sibling ul show class:

$('#menu-market-intelligence-bar>li.dropdown>a').click( function(e){

    $('ul').not($(this).siblings('ul')).removeClass('show');
    $(this).siblings('ul').toggleClass('show');

    e.preventDefault();
  });

Upvotes: 1

Related Questions