天道酬勤,学无止境

Prevent Bootstrap dropdown from closing on clicks [duplicate]

Question

My menu uses Bootstrap 3 and I can't prevent dropdown from closing on click. How can I do it?

JSFiddle

 // Add open class if active
  $('.sidebar-nav').find('li.dropdown.active').addClass('open');

  // Open submenu if active
  $('.sidebar-nav').find('li.dropdown.open ul').css("display","block");

  // Change active menu
  $(".sidebar-nav > li").click(function(){
    $(".sidebar-nav > li").removeClass("active");
    $(this).addClass("active");
  });

  // Add open animation
  $('.dropdown').on('show.bs.dropdown', function(e){
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
  });

  // Add close animation
  $('.dropdown').on('hide.bs.dropdown', function(e){
    $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
  });
Answer1

You need to stop event from bubbling up the DOM tree:

$('.dropdown-menu').click(function(e) {
    e.stopPropagation();
});

event.stopPropagation prevents event from reaching the node where it's eventually handled by Bootstrap hiding menu.

Demo: http://jsfiddle.net/wkc5md23/3/

Answer2

I believe this should be a more proper solution, as stopping propagation on the click event might sometimes cause issues later on in development. You may read more into it here: http://css-tricks.com/dangers-stopping-event-propagation/ Instead this solution stops propagation on the Bootstrap hide (hide.bs.dropdown) event, which stops it from continuing on to the hidden (hidden.bs.dropdown) event.

The following code has been taken and edited by myself to make it work on all Bootstrap dropdowns, as it has originally been taken from here: Preventing bootstrap dropdown from closing on click I personally prefer this way also because it uses the built in Bootstrap dropdown events, which could be found here: https://getbootstrap.com/docs/3.4/javascript/#dropdowns-events.

  $(function() {
      $('.dropdown').on({
          "click": function(event) {
            if ($(event.target).closest('.dropdown-toggle').length) {
              $(this).data('closable', true);
            } else {
              $(this).data('closable', false);
            }
          },
          "hide.bs.dropdown": function(event) {
            hide = $(this).data('closable');
            $(this).data('closable', true);
            return hide;
          }
      });
  });
Answer3

You can disable the dropdown functionality temporarily. This is a workaround.

Example with input field inside the drop-down "menu":

    //for dropdown field not closing when clicking on inputfield
    $(document).on('focus', 'input', function(e) {

  // this attribute can be anything except "dropdown", you can leave it blank 
      $('#yourDropdownID').attr('data-toggle','off'); 

    });

    //for dropdown field back to normal when not on inputfield
    $(document).on('focusout', 'input', function(e) {

      $('#yourDropdownID').attr('data-toggle','dropdown');

    });

This can be used on anything that is clickable and you can define individually what items clicked can close or not close the drop-down menu.

Answer4

Not close in click out side menu

$(function() {
   var closeble = false;
   $('body').on('click', function (e) {
       if (!$(event.target).is("a.dropdown-toggle")) {
           closeble = false;
       }

   });
   $('.dropdown').on({
       "click": function(event) {
           if ($(event.target).closest('.dropdown-toggle').length) {
               closeble = true;
           } else {
               closeble = false;
           }
       },
       "hide.bs.dropdown": function() {
           return closeble;
       }
   });
});

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • Prevent bootstrap dropdown closing when clicked anywhere else other than the menu item itself
    Question I need the submenu to be opened when its child is active (as in when the user is on that page). Managed to do so already by this: // To open active submenu on load jQuery('.keep-open').find('.current-menu-item').closest('.current-menu-parent').children('.dropdown-toggle').trigger('click'); But upon clicking anywhere, the menu closes. It needs to stay opened unless it's specifically clicked. Only managed to prevent it from closing when clicked outside using this: // To prevent submenu from being closed on outside click jQuery('.current-menu-parent').on('hide.bs.dropdown', function() {
  • Keep Bootstrap Dropdown Open When Clicked Off
    Question If the dropdown is visible, and I click outside the dropdown it closes. I need it to not close. From the documentation: When opened, the plugin also adds .dropdown-backdrop as a click area for closing dropdown menus when clicking outside the menu. What JavaScript can I add to prevent the drop down from closing? Answer1 From the events section of the Bootstrap dropdown documentation: hide.bs.dropdown: This event is fired immediately when the hide instance method has been called. For starters, to prevent the dropdown from closing, we can just listen to this event and stop it from
  • Bootstrap dropdown closing when clicked
    Question I put a form inside a bootstrap dropdown, but when I click any of the fields in the form, the dropdown goes away. I have this piece of code but I don't know where to put it to prevent the dropdown disappearing. $(function test() { // Setup drop down menu $('.dropdown-toggle').dropdown(); // Fix input element click problem $('.dropdown input, .dropdown label').click(function(e) { e.stopPropagation(); }); }); Could someone please tell me where I should put this? I tried in the bootstrap-dropdown, I tried within the HTML but it still doesn't work. Answer1 Simply use this example.This
  • Bootstrap dropdown disappear with right-click on Firefox
    Question I have some kind of problem with twitter-bootstrap and firefox. I have a button and a dropdown menu with an input text. If I right click on the input ( for right-click + Paste for example), firefox closes the dropdown. And that quite boring. Is there any solution for prevent that behaviour ? Thanks ! Answer1 As an immediate stop-gap workaround you can use something along the following lines to prevent the click event from propagating when the click event is a right-click JS $(document).on('click', function(e) { e.button === 2 && e.stopImmediatePropagation() }) This would need to be
  • Twitter bootstrap stop propagation on dropdown open
    Question I have a twitter bootstrap dropdown inside a div with the plugin jOrgChart. The problem I'm having is that when I click the button to open the dropdown menu it also triggers a click event in the parent div that does a collapse of other elements. This is my html: <div id="chart"> <div class="node"> <div class="btn-group"> <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"> Actions <span class="caret"></span> </a> <ul class="dropdown-menu" style="text-align:left;"> <li><a href="#">Edit</a></li> <li><a href="#">Delete</a></li> </ul> </div> </div> <div class="node"> ... </div>
  • Bootstrap dropdown disappears on input select
    Question I have a Bootstrap dropdown menu I plan to use to login. It appears fine but when I select the username nput it vanishes since the focus has gone to the input. How would I go about adding in support for the inputs or is there a working method for this? My current code is: <li id="fat-menu" class="dropdown"> <a href="#" id="drop3" role="button" class="dropdown-toggle" data-toggle="dropdown" data-target="#">Login <b class="caret"></b></a> <ul class="dropdown-menu" role="menu" aria-labelledby="drop3"> <li role="presentation"><input name="username" type="text" placeholder="Username" /><
  • Avoid dropdown menu close on click inside
    Question I have a Twitter Bootstrap dropdown menu. As all Twitter Bootstrap users know, the dropdown menu closes on click (even clicking inside it). To avoid this, I can easily attach a click event handler on the dropdown menu and simply add the famous event.stopPropagation(). <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
  • Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape? [duplicate]
    Question This question already has answers here: Disallow Twitter Bootstrap modal window from closing (21 answers) Closed 1 year ago. I'm using the Twitter Bootstrap modal as a wizard window, and would like to prevent the user from closing it when clicking outside of the modal or when pressing escape. Instead, I want it to be closed when the user presses the finish button. How could I achieve this scenario? Answer1 If using JavaScript then: $('#myModal').modal({ backdrop: 'static', keyboard: false }) or in HTML: <a data-controls-modal="your_div_id" data-backdrop="static" data-keyboard="false"
  • Avoid having to double-click to toggle Bootstrap dropdown
    Question I am using a Bootstrap dropdown menu. The problem is that it never drops down upon the first click; I need to click 2 times for it to be toggled. I guess the click event is somehow getting stuck somewhere before propagating down... Is there any way to fix that? Answer1 If someone is using angular with ui-bootstrap module along with normal bootstrap HTML dropdown definition, there are also two clicks needed. <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a> [...] </li> => Removing the data-toggle="dropdown" will fix the issue. Opening the
  • dropdown closes on focus
    Question I want to trigger dropdown open on focus on input field. But it openes and suddenly closes every time I focus. With button toggle everything is ok. Here is example: http://codepen.io/piernik/pen/ByKRwE Here is HTML <div class="input-group"> <input type="text" class="form-control" ng-focus="show($event)"> <div class="input-group-addon"><i class="fa fa-fw fa-calendar"></i></div> </div> <a class="btn btn-default" ng-click="toggleDropdown($event)">toggle</a> <div class="dropdown" dropdown is-open="model.open"> <ul class="dropdown-menu" role="menu"> Content </ul> </div> And JS: $scope
  • Stop propagation of underlying ng-click inside a jQuery click event
    Question A Twitter Bootstrap dropdown is nested inside a tr. The tr is clickable through ng-click. Clicking anywhere on the page will collapse the dropdown menu. That behavior is defined in a directive through $document.bind('click', closeMenu). So, when menu is opened, and the user click on a row, I want the menu to close (as it does) AND I want to prevent the click event on the row. JSFiddle : http://jsfiddle.net/LMc2f/1/ JSFiddle + directive inline : http://jsfiddle.net/9DM8U/1/ Relevant code from ui-bootstrap-tpls-0.10.0.js : angular.module('ui.bootstrap.dropdownToggle', []).directive(
  • Prevent the disappear of Dropdown menu using bootstrapDropdown when clicking on the list
    Question I am using using bootstrap-dropdown to generate a Dropdown menu. I would like to prevent the disappearing of the menu when click on it. I have implemented the following code, but it does not work. Any idea how to fix it? HTML <li class="dropdown notification"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="notification-label label label-info"> <i class="icon-inbox icon-white"></i> <span class="notification-number">{{ unread_notifications }}</span> </span> </a> <ul class="dropdown-menu notification-list"></ul> </li> JS events: { 'click ul.notification-list':
  • Keep Bootstrap dropdown open on click
    Question I use a bootstrap dropdown as a shoppingcart. In the shopping cart is a 'remove product' button (a link). If I click it, my shoppingcart script removes the product, but the menu fades away. Is there anyway way to prevent this? I tried e.startPropagation, but that didn't seem to work: <div id="shoppingcart" class="nav-collapse cart-collapse"> <ul class="nav pull-right"> <li class="dropdown open"> <a href="#" data-toggle="dropdown" class="dropdown-toggle">Totaal: € 43,00</a> <ul class="dropdown-menu"> <li class="nav-header">Pakketten</li> <li> <span class="quantity">1x</span> <span
  • twitter bootstrap dropdown links not working
    Question I am using bootstrap version 2.0 I have the following html structure - Now when I click on the Filter by Team the dropdown shows properly. Now when I click on the link, I should be taken to the page. But the links do not work. I mean, when I click on the dropdown elements, they should take me to a url, which they are href'ed to, this does not happen. <li style="margin-left: 12px;"> <div class="dropdown" style="margin-top: 5px;"> <a class="dropdown-toggle" style="margin-left: -2px;" data-toggle="dropdown" href="#"> Filter by Team </a> <ul class="dropdown-menu" data-toggle="dropdown"
  • How to implement a Navbar Dropdown Hover in Bootstrap v4?
    Question I am a bit confused on the new bootstrap version since they changed dropdown menus to divs: <nav class="navbar navbar-toggleable-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav
  • How to make Twitter Bootstrap menu dropdown on hover rather than click
    Question I'd like to have my Bootstrap menu automatically drop down on hover, rather than having to click the menu title. I'd also like to lose the little arrows next to the menu titles. Answer1 I created a pure on hover dropdown menu based on the latest (v2.0.2) Bootstrap framework that has support for multiple submenus and thought I'd post it for future users: body { padding-top: 60px; padding-bottom: 40px; } .sidebar-nav { padding: 9px 0; } .dropdown-menu .sub-menu { left: 100%; position: absolute; top: 0; visibility: hidden; margin-top: -1px; } .dropdown-menu li:hover .sub-menu {
  • Twitter Bootstrap: How to create a dropdown button with an accordion inside it?
    Question In Twitter Bootstrap, I am trying to create a button dropdown with an accordion inside it. the purpose is to present a long list of items in a concise form (i.e. avoid long scroll-downs by the user). the straightforward way of including an accordion div inside a dropdown div does not work..: <div class="dropdown"> <a data-toggle="dropdown" href="#">Dropdown trigger</a> <div class="dropdown-menu" role="menu" aria-labelledby="dLabel" id="accordion"> <h3>Unit 1</h3> <div> <p>item a</p> <p>item b</p> </div> <h3>Unit 2</h3> <div> <p>item c</p> <p>item d</p> <p>item e</p> </div> </div> <
  • jQuery e.stopPropagation() - how to use without breaking dropbox functionality altogether?
    Question Short story: stopPropagation() prevents a dropdown menu from closing - which is good. But it also prevents the dropbox from opening next time around - which is bad. Long story: I'm using Twitter-Bootstrap and I've put a search box inside the dropdown menu like so: <div id="search_word_menu" style="position:absolute;right:157px;top:60px;"> <ul class="nav nav-pills"> <li class="dropdown" id="menu200"> <a class="dropdown-toggle btn-inverse" data-toggle="dropdown" style="width:117px;position:relative;left:2px" href="#menu200"> <i class="icon-th-list icon-white"></i> Testing <b class=
  • Stop just one dropdown toggle from closing on click
    Question I have a button dropdown (just one, not all of them), and inside of it, I want to have several input field where people can type stuff inside without the dropdown hiding as soon as you click on it (but it does close if you click outside of it). I created a jsfiddle: http://jsfiddle.net/denislexic/8afrw/2/ And here is the code, it's basic: <div class="btn-group" style="margin-left:20px;"> <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"> Action <span class="caret"></span> </a> <ul class="dropdown-menu"> <!-- dropdown menu links --> <li>Email<input type="text" place-holder
  • Keep Bootstrap Dropdown Open When Clicked Inside
    Question I have a bootstrap dropdown menu. I want it to be kept open when I click inside it, but closed when clicking the dropdown toggle button or outside of the menu. It seems like the dropdown does not close when I type something in the input but it closes when I click anywhere else inside the dropdown. Q: How can I avoid this by using jQuery? Below is my HTML: <div id="navbar"> <nav class="navbar navbar-default navbar-static-top" role="navigation"> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="#" class="dropdown