I have a menu bar with a number of parent and child menu items:
<nav>
<ul>
<li class="menu-item-has-children">
<a href="#">Parent item</a>
<ul>
<li><a href="#">Child item</a></li>
<li><a href="#">Child item</a></li>
</ul>
</li>
<li class="menu-item-has-children">
<a href="#">Parent item</a>
<ul>
<li><a href="#">Child item</a></li>
<li><a href="#">Child item</a></li>
</ul>
</li>
</ul>
</nav>
The child submenu is by default hidden:
.menu-item-has-children > ul {
display: none;
}
I'd like to achieve the following:
- When the top level menu item is clicked, I would like to toggle (show/hide) its associated submenu and hide any other submenus that might be opened.
- When anywhere else on the page is clicked other than the submenu or its parent item, I'd like to hide all submenus.
I'm using the following code, but instead of showing the correct submenu it shows/hides all submenus:
$(document).on('click', function(e) {
if($(e.target).parent().hasClass('menu-item-has-children')) {
$(this).find('ul').show();
} else {
$('.menu-item-has-children > ul').toggle();
}
});
See fiddle: https://jsfiddle.net/gs9q6kwh/
Any idea what I am doing wrong?