I’m trying to put together a navigation menu that uses click instead of hover to display the 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-menuitem that’svisibleandslideToggleit.Here’s a fiddle