I’ve tried this code below. I expected that the dropdown menu could hide when I clicked other elements. However, I duplicated a same li with the same class name. I clicked the first "Product" dropdown, then I clicked the other "Product", but the first dropdown menu didn’t hide.
Could anyone help me out with this? I am a JavaScript beginner. Thank you so much!!
$(document).ready(function() {
// Show hide popover
$(".dropdown").click(function() {
$(this).find(".dropdown-menu").slideToggle("fast");
});
});
$(document).on("click", function(event) {
var $trigger = $(".dropdown");
if ($trigger !== event.target && !$trigger.has(event.target).length) {
$(".dropdown-menu").slideUp("fast");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li class="dropdown">
<a href="#">Products ▾</a>
<ul class="dropdown-menu">
<li><a href="#">Laptops</a></li>
<li><a href="#">Monitors</a></li>
<li><a href="#">Printers</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#">Products ▾</a>
<ul class="dropdown-menu">
<li><a href="#">Laptops</a></li>
<li><a href="#">Monitors</a></li>
<li><a href="#">Printers</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
</body>
2
Answers
meabe:
On
click
event, you can close all dropdowns with$(".dropdown-menu").slideUp("fast");
, and then open just the selected one with$(this).children(".dropdown-menu").slideDown("fast");
.