Search code examples
jquerytwitter-bootstrap-3dropdownstoppropagation

Jquery 'document on click' doesn't work when Bootstrap dropdown-toggle fires


The Problem

I have an event listener that hides a dropdown (by removing a class) when a click happens outside of the dropdown:

$(document).on('click', function(event) {
 if (!$(event.target).closest('#myDropdown').length) {
      $('#myDropdown').removeClass("show-menu");
 }
});

It works perfectly, except when I click on a bootstrap dropdown (that uses the class '.dropdown-toggle). In that case my dropdown stays open while the bootstrap dropdown is also open. The click event is never heard in DOM.


Solution

  • Update: After a lot of struggle I found the answer:

    For some unknown reason, Bootstrap .dropdown-toggle includes a stopPropagation. So when it's clicked it, nothing else in the document tree is heard. My solution was to explicitly include an event listener for the .dropdown-toggle class in addition to my document listener.

          $(document).on('click', function(event) {
            if (!$(event.target).closest('#myDropdown').length) {
              $('#myDropdown').removeClass("show-menu");
            }
          });
    
          //listens for Bootstrap .dropdown-toggle
          $('.dropdown-toggle').on('click', function(event) {
            if (!$(event.target).closest('#myDropdown').length) {
              $('#myDropdown').removeClass("show-menu");
            }
          });
    

    If anybody has a better solution I'm happy to mark it as the correct answer!