jQuery drop down menu closing by clicking outside jQuery drop down menu closing by clicking outside javascript javascript

jQuery drop down menu closing by clicking outside


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


how to have a click event outside of the dropdown menu so that it close the dropdown menu ?Heres the code

$(document).click(function (e) {    e.stopPropagation();    var container = $(".dropDown");    //check if the clicked area is dropDown or not    if (container.has(e.target).length === 0) {        $('.subMenu').hide();    }})


Stopping Event Propagation in some particular elements ma y become dangerous as it may prevent other some scripts from running. So check whether the triggering is from the excluded area from inside the function.

$(document).on('click', function(event) {  if (!$(event.target).closest('#menucontainer').length) {    // Hide the menus.  }});

Here function is initiated when clicking on document, but it excludes triggering from #menucontainer.For details https://css-tricks.com/dangers-stopping-event-propagation/