Reputation: 3746
I have a bootstrap dropdown menu:
<div class="dropdown>
<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown"><img src="@imagePath" class="img-circle dropbtn" alt="Product" style="width:30px;height:30px;" /></a>
<ul class="dropdown-menu" id="productDD" role="menu" aria-labelledby="menu1"></ul>
</div>
Now the ul load the products on page load through ajax call. The issue is when I click any product in the dropdown, the dropdown gets closed. But I want to close dropdown only when mouse is clicked anywhere outside of the ul
Upvotes: 9
Views: 14087
Reputation: 277
Bootstrap has a built-in solution
<a class="dropdown-toggle" href="#" id="menu1"
data-toggle="dropdown"
data-bs-auto-close="outside">
<img ... />
</a>
Upvotes: 3
Reputation: 1002
In 2021 you do it this way:
$('.dropdown').on({
"shown.bs.dropdown": function() { /* whatever you want to do when it fires */ },
"click": function(e) { // handles click event
console.log(e.target) // just to check which element is on top
if($('.dropdown-menu').is(e.target)) { // if dropdown is clicked
this.closable = false // do not close it
return;
} else {
this.closable=true; // else close it
}
},
"hide.bs.dropdown": function() { return this.closable; } // save state
});
}
Upvotes: 1
Reputation: 608
Try something like this:
$(document).click(function(e) {
// get the clicked element
$clicked = $(e.currentTarget);
// if the clicked element is not a descendent of the dropdown
if ($clicked.closest('.dropdown').length === 0) {
// close the dropdown
$('.dropdown').removeClass('open');
}
});
Upvotes: 3
Reputation: 593
just place this script in your code
<script>
$(document).click(function() {
$(".dropdown").removeClass('open');
});
</script>
Upvotes: 0