Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close bootstrap dropdown only when mouse is clicked outside of dropdown

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

like image 780
Ask Avatar asked Sep 04 '18 12:09

Ask


People also ask

How do you close a drop down when clicking outside?

Answer: Use the jQuery on() method You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.

How do I stop dropdown menu Close menu items on clicking inside?

Removing the data attribute data-toggle="dropdown" and implementing the open/close of the dropdown can be a solution. Save this answer.

How do I toggle a dropdown in bootstrap?

Via data attributesAdd data-toggle="dropdown" to a link or button to toggle a dropdown.

How set dropdown position in bootstrap?

By default, a dropdown menu is automatically positioned 100% from the top and along the left side of its parent. Add . dropdown-menu-right to a . dropdown-menu to right align the dropdown menu.


1 Answers

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');
  }
});
like image 118
Matt Dietsche Avatar answered Sep 29 '22 21:09

Matt Dietsche