7

I have a bootstrap dropdown menu:

<div class="dropdown>
   <a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown"><img src="@imagePath" class="img-circle dropbtn" alt="Product" style="width:30px;height:30px;" /></a>

  <ul class="dropdown-menu" id="productDD" role="menu" aria-labelledby="menu1"></ul>
</div>

Now the ul load the products on page load through ajax call. The issue is when I click any product in the dropdown, the dropdown gets closed. But I want to close dropdown only when mouse is clicked anywhere outside of the ul

Ask
  • 3,076
  • 6
  • 30
  • 63

4 Answers4

2

Try something like this:

$(document).click(function(e) {
  // get the clicked element
  $clicked = $(e.currentTarget);
  // if the clicked element is not a descendent of the dropdown
  if ($clicked.closest('.dropdown').length === 0) {
    // close the dropdown
    $('.dropdown').removeClass('open');
  }
});
Matt Dietsche
  • 578
  • 5
  • 17
2

Bootstrap has a built-in solution

<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown" data-bs-auto-close="outside"><img ... /></a>

yih613
  • 239
  • 1
  • 10
1

In 2021 you do it this way:

$('.dropdown').on({
    "shown.bs.dropdown": function() { /* whatever you want to do when it fires */ },
    "click":             function(e) { // handles click event
      
       console.log(e.target) // just to check which element is on top

      if($('.dropdown-menu').is(e.target)) { // if dropdown is clicked
        this.closable = false // do not close it
        return;
      } else {
        this.closable=true; // else close it 
      }

    },
    "hide.bs.dropdown":  function() { return this.closable; } // save state
  });
}
Ivan Kolyhalov
  • 902
  • 11
  • 16
0

just place this script in your code

<script>
    $(document).click(function() {
    $(".dropdown").removeClass('open');
});
</script>
Girish Ninama
  • 583
  • 4
  • 8
  • thanks for the answer but it didn't work unfortunately. I don't want to close dropdown when mouse is clicked inside of a ul "productDD" – Ask Sep 04 '18 at 12:30
  • Maybe try to use `blur` event? As said [here](https://api.jquery.com/blur/) `The blur event is sent to an element when it loses focus. (...) In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.` – Jacek Rosłan Sep 04 '18 at 12:39