Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery drop down menu closing by clicking outside

I am developing a simple dropdown menu with jQuery . When a user press on a trigger area, it will toggle the dropdown area. My question is how to have a click event outside of the dropdown menu so that it close the dropdown menu ?

like image 421
user670800 Avatar asked Jun 24 '11 04:06

user670800


People also ask

How do I close a drop down when I click 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 toggle a drop down menu?

To open the dropdown menu, use a button or a link with a class of . dropdown-toggle and the data-toggle="dropdown" attribute. The . caret class creates a caret arrow icon (), which indicates that the button is a dropdown.


1 Answers

You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.

/* Anything that gets to the document    will hide the dropdown */ $(document).click(function(){   $("#dropdown").hide(); });  /* Clicks within the dropdown won't make    it past the dropdown itself */ $("#dropdown").click(function(e){   e.stopPropagation(); }); 

Demo: http://jsbin.com/umubad/2/edit

like image 102
Sampson Avatar answered Sep 28 '22 16:09

Sampson