Prevent Bootstrap dropdown from closing on clicks

Kasara picture Kasara · Oct 29, 2014 · Viewed 35.5k times · Source

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

Answer

dfsq picture dfsq · Oct 29, 2014

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/