Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent my dropdown from closing when clicking inside it?

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>
like image 655
Vanquiza Avatar asked Apr 12 '14 14:04

Vanquiza


2 Answers

'.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();
});
like image 166
Vanquiza Avatar answered Nov 13 '22 11:11

Vanquiza


Bootstrap 5 has now an autoclose feature where you can configure this behavior.

like image 41
tmsss Avatar answered Nov 13 '22 09:11

tmsss