I have a dropdown menu that on click, displays a submenu of list items. Everything works great except the PARENT 2 submenu, if active, does NOT turn off if I click on the PARENT 3 link with a dropdown.
$(function () {
$('nav ul li a:not(:only-child)').click(function (e) {
$(this).siblings('.nav-dropdown').toggle();
$('.dropdown').not($(this).siblings()).hide();
e.stopPropagation();
});
$('html').click(function () {
$('.nav-dropdown').hide();
});
});
So if I click PARENT 2, the dropdown appears. If I then click PARENT 3, its dropdown also appears (and I need PARENT 2 dropdown to disappear). How to make sure that any menu item clicked removes any instance of an open submenu?
<nav>
<ul >
<li><a href="#">Parent 1</a></li>
<li><a href="#">Parent 2</a>
<ul >
<li>
<a href="#">Child 1</a>
</li>
<li>
<a href="#">Child 2</a>
</li>
</ul>
</li>
<li><a href="#">Parent 3<i ></i></a>
<ul >
<li>
<a href="#">Child 1</a>
</li>
<li>
<a href="#">Child 2</a>
</li>
</ul>
</li>
<li><a href="#">Parent 4</a></li>
</ul>
</nav>
CodePudding user response:
Your problem was that there isn't any element with the class dropdown
.
So $('.dropdown').not($(this).siblings()).hide();
didn't work.
Try this:
$(function() {
$('nav ul li a:not(:only-child)').click(function(e) {
$(this).siblings('.nav-dropdown').toggle();
$('.nav-dropdown').not($(this).siblings()).hide();
e.stopPropagation();
});
$('html').click(function() {
$('.nav-dropdown').hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
<ul >
<li><a href="#">Parent 1</a></li>
<li><a href="#">Parent 2</a>
<ul >
<li>
<a href="#">Child 1</a>
</li>
<li>
<a href="#">Child 2</a>
</li>
</ul>
</li>
<li><a href="#">Parent 3<i ></i></a>
<ul >
<li>
<a href="#">Child 1</a>
</li>
<li>
<a href="#">Child 2</a>
</li>
</ul>
</li>
<li><a href="#">Parent 4</a></li>
</ul>
</nav>