1

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.

0

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

does not wok here :-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.