I'm using Bootstrap to create a dropdown for my website, but I am having some problems with it.
On my website, if clicked on "Select Populations" the popup will appear (FYI: clicking "submit" will have things appear in it). And when I click inside of it, it always closes down. How can I prevent it from doing so? I only want it to close if clicked outside of the field.
Here's the code I use:
CSS:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
.dropdown-menu:before {
position: absolute;
top: -7px;
left: 9px;
display: inline-block;
border-right: 7px solid transparent;
border-bottom: 7px solid #ccc;
border-left: 7px solid transparent;
border-bottom-color: rgba(0, 0, 0, 0.2);
content: '';
}
.dropdown-menu:after {
position: absolute;
top: -6px;
left: 10px;
display: inline-block;
border-right: 6px solid transparent;
border-bottom: 6px solid #ffffff;
border-left: 6px solid transparent;
content: '';
}
HTML:
<div class="dropdown">
<button data-toggle="dropdown" id="submitButton" type="button" id="pops" >Select Populations</button>
<ul id="popupDropDown" class="dropdown-menu" role="menu" aria-labelledby="dLabel">
</ul>
</div>
'.dropdown-menu'
catches the the bubble. There is no need to catch elements inside of the dropdown in this case.
e.stopPropagation()
prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('.dropdown-menu').on('click', function(e) {
e.stopPropagation();
});
Bootstrap 5 has now an autoclose feature where you can configure this behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With