user670800 user670800 - 3 months ago 17
jQuery Question

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 ?

Answer

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