I want to hide the dropdown menu (close it) when this option is clicked.
// hide the menu when an example is clicked
$(".dropdown-item").on("click", function(){
$(".dropdown-menu").hide();
});
I have tried the below which I found online, but it doesn't seem to close the menu:
// hide the menu when an example is clicked $(".dropdown-item").on("click", function(){ $(".dropdown-menu").hide(); });
$( document ).ready(function() { debugger; var ele=$(".dropdown-content"); $(".dropdown-content a").click(function(){ if(this.innerText=="Link 2"){ $(".dropdown-content").hide(); $(".dropbtn").hide(); } }); });
.dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; }.dropdown { position: relative; display: inline-block; }.dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; }.dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; }.dropdown-content a:hover {background-color: #f1f1f1}.dropdown:hover.dropdown-content { display: block; }.dropdown:hover.dropbtn { background-color: #3e8e41; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2>Dropdown Menu</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <div class="dropdown"> <button class="dropbtn">Dropdown</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div>
You hide a dropdown menu like this and if you want to show simply add show functionality.
Try this toggle method should work
<a href="#" onclick="handleClick()" class="btn btn-floating" data-toggle="dropdown">
how/hide menu
</a>
function handleClick(){
$(".dropdown-menu").toggle();
}
refer to this link for running example:
Just remove class 'show' from dropdown:
// hide the menu when an example is clicked
$(".dropdown-item").on("click", function(el){
$(el.target).parents(".dropdown").removeClass("show");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.