Reputation: 1751
I have a simple Bootstrap 3 dropdown menu that I want to keep open at all times except when clicking on the element(anchor) that opened it. So the same element should be responsible for showing and hiding the dropdown. I want to be able to click everywhere in the UI except the element that opens and closes the dropdown.
I have tried many different approaches to solve this with e.stopPropagation();
. I have tried it with jQuery .off()
function..
I successfully managed to solve the problem of keeping the dropdown open when clicking inside the dropdown menu with the following code, but whenever clicking outside it closes the menu:
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown" data-toggle="dropdown" role="menu"><i class="fa fa-sort-alpha-asc"></i></a>
<!-- Dropdown Menu -->
<ul class="dropdown-menu" role="menu">
<li>
// Menu content
</li>
</ul>
</li>
</ul>
<script>
$(document).on('click', '.dropdown .dropdown-menu', function (e) {
e.stopPropagation();
});
</script>
Upvotes: 0
Views: 516
Reputation: 143
A solution could be to bind to click events on the body, and check if you pressed the link for the dropdown.
If you click the link for the dropdown, save that in a variable (pressedLink).
When the event runs for hiding the dropdown, return the pressedLink variable. If you return false from the event, nothing more will happen, and the dropdown stays open.
var pressedLink = false;
$("body").on("click", function(e) {
if (e.target.id === "only-toggle-when-pressing-me") {
pressedLink = true;
} else {
pressedLink = false;
}
});
$('.dropdown').on('hide.bs.dropdown', function () {
return pressedLink;
})
#wrapper {
background-color: red;
padding: 20px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.nav {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div id="wrapper">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown" data-toggle="dropdown" role="menu"><i id="only-toggle-when-pressing-me" class="fa fa-sort-alpha-asc">link</i></a>
<!-- Dropdown Menu -->
<ul class="dropdown-menu" role="menu">
<li>
// Menu content
</li>
</ul>
</li>
</ul>
</div>
Upvotes: 1