jquery drop down menu closing by clicking outside

user670800 picture user670800 · Jun 24, 2011 · Viewed 137.3k times · Source

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 ?

Answer

Sampson picture Sampson · Jun 24, 2011

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