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 >
<a href="#">Products ▾</a>
<ul >
<li><a href="#">Laptops</a></li>
<li><a href="#">Monitors</a></li>
<li><a href="#">Printers</a></li>
</ul>
</li>
<li >
<a href="#">Products ▾</a>
<ul >
<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>
CodePudding user response:
meabe:
$(".dropdown").click(function() {
// when click to the element dropdown required close all dropdowns first
$(".dropdown").each((element,i)=>{
$(element).find(".dropdown-menu").slideUp("fast");
});
//then open this
$(this).find(".dropdown-menu").slideToggle("fast");
});
CodePudding user response:
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");
.
$(document).ready(function() {
// Show hide popover
$(".dropdown").click(function() {
if (!$(this).children(".dropdown-menu").is(":visible")) {
$(".dropdown-menu").slideUp("fast");
$(this).children(".dropdown-menu").slideDown("fast");
} else {
$(".dropdown-menu").slideUp("fast");
}
});
});
.dropdown-menu {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li >
<a href="#">Products ▾</a>
<ul >
<li><a href="#">Laptops</a></li>
<li><a href="#">Monitors</a></li>
<li><a href="#">Printers</a></li>
</ul>
</li>
<li >
<a href="#">Products ▾</a>
<ul >
<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>