javascripttwitter-bootstrapdrop-down-menujsfiddle

Prevent Bootstrap dropdown from closing on clicks


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

Solution

  • 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/