Prevent Bootstrap dropdown from closing on clicks [duplicate]

怎甘沉沦 提交于 2019-11-28 12:06:32

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/

yaharga

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: http://getbootstrap.com/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;
          }
      });
  });

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;
    }
});

});

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!