开发者

jQuery animating sub-menus on click

I'm trying to put together a navigation menu that uses click instead of hover to display t开发者_JAVA技巧he sub-menus (or dropdowns).

I have it set up but it's not quite working. I don't know how to close the currently open sub-menu when clicking on another.

HTML:

<ul id="menu-primary-navigation" class="menu nav-main">

  <li class="nav-about"><a href="#">About us</a>
    <ul class="sub-menu" style="display: none; ">
      <li><a href="/what-we-do/">What we do</a></li>
      <li><a href="/why-we-do-it/">Why we do it</a></li>
    </ul>
  </li>

  <li class="nav-weare"><a href="#">Who we are</a>
    <ul class="sub-menu" style="display: none; ">
      <li><a href="/who-we-are/ambassadors/">Ambassadors</a></li>
      <li><a href="/who-we-are/trustees/">Trustees</a></li>
    </ul>
  </li>

  <li class="nav-involved"><a href="#">Get involved</a>
    <ul class="sub-menu" style="display: none; ">
      <li><a href="/get-involved/coach/">Become a coach</a></li>
      <li><a href="/get-involved/academy/">Become an academy</a></li>
    </ul>
  </li>

</ul>

Currently to get each sub-menu to show and hide I use this jQuery:

$('#menu-primary-navigation li a').click(function(e) {
    e.preventDefault();
    $(this).next('.sub-menu').slideToggle('fast');
});

But the problem is they work independently and go over the top of each other (all can be open at once).

I need a way to detect a click of another top level link that closes any currently open sub-menus and shows the sub-menu for the clicked link.


You can select the sub-menu item that's visible and slideToggle it.

Here's a fiddle

$('#menu-primary-navigation > li > a').click(function(e) {  // select only the child link and not all links, this prevents sub links from being selected. 
    var sub_menu = $(this).next('.sub-menu'); // store the current submenu to be toggled  
    e.preventDefault();
    $('.sub-menu:visible').not(sub_menu).slideToggle('fast'); // select all visible sub menus excluding the current one that was clicked on and close them 
    sub_menu.slideToggle('fast'); // toggle the current sub menu 
});


On your sub-menu click events you could add a class 'submenuopen'

$(this).addClass('submenuopen')

On your parent click events, look for elements that contain that class. Remove the class and hide the elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜