Prevent closing on click inside dropdown menu
In Twitter Bootstrap, dropdown menu will close on click (even click inside menu) . To avoid this, you can attach a click event handler to the dropdown and add the famous event.stopPropagation().
<code class="html"><ul class="nav navbar-nav"> <li class="dropdown mega-dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-list-alt"></i> Menu item 1 <span class="fa fa-chevron-down pull-right"></span> </a> <ul class="dropdown-menu mega-dropdown-menu"> <li> <div id="carousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-slide-to="0" data-target="#carousel"></li> <li class="active" data-slide-to="1" data-target="#carousel"></li> </ol> <div class="carousel-inner"> <div class="item"> <img alt="" class="img-rounded" src="img1.jpg"> </div> <div class="item active"> <img alt="" class="img-rounded" src="img2.jpg"> </div> </div> <a data-slide="prev" role="button" href="#carousel" class="left carousel-control"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a data-slide="next" role="button" href="#carousel" class="right carousel-control"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </li> </ul> </li> </ul></code>
This method seems easy and very common, but because the event handlers of carousel-controls (and carousel indicators) are delegated to the document object, it is not suitable for these elements (prev/next controls, etc. ) will be "ignored".
<code class="js">$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event){ // 不会向document 节点传播事件 // 所以委托的事件不会被触发 event.stopPropagation(); });</code>
Relying on Twitter Bootstrap's dropdown hide/hidden events is not a solution for the following reasons:
The following is a fiddle demo of normal behavior and a fiddle demo with event.stopPropagation() added.
Update
Thanks Roman for the answer. I also found another answer, as follows:
<code class="js">$(document).on('click', 'someyourContainer .dropdown-menu', function (e) { e.stopPropagation(); });</code>
The above is the detailed content of How to Prevent Bootstrap Dropdown from Closing When Clicking Inside?. For more information, please follow other related articles on the PHP Chinese website!