Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Bootstrap dropdown from closing on clicks [duplicate]

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();
  });
like image 969
Kasara Avatar asked Oct 29 '14 19:10

Kasara


People also ask

How do I stop bootstrap dropdown from closing?

This behavior can be changed by using the autoClose property. By default, autoClose is set to the default value true and behaves like expected. By choosing false, the dropdown menu can only be toggled by clicking on the dropdown button.

How do I stop a dropdown from closing on click?

Removing the data attribute data-toggle="dropdown" and implementing the open/close of the dropdown can be a solution. This solution is working fine.

How do I stop dropdown menu to close menu items on clicking outside?

Answer: Use the jQuery on() method You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.

How do I keep my drop down menus open?

Set toggle={false} property inside DropdownItem to prevent dropdown from closing.


1 Answers

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/

like image 104
dfsq Avatar answered Oct 02 '22 22:10

dfsq