Reputation: 2779
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>
Upvotes: 12
Views: 25092
Reputation: 1030
Use data-bs-toggle
parameter in the button
html tag.
Example:
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false"> Clickable inside</button>
the value of data-b-toggle can be data-bs-auto-close="true" or "false"
or data-bs-auto-close="outside" or "inside"
i have tried this in my code. Its working fine.
Upvotes: 1
Reputation: 2119
Bootstrap 5 has now an autoclose feature where you can configure this behavior.
Upvotes: 12
Reputation: 2779
'.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();
});
Upvotes: 22