JavaScript Function for hiding any kind of menu or div when clicking outside the space of that menu or div. To find the info regarding the clicked element, we can use event function of JavaScript and compare the currently clicked target element with your desired menu or div target. If comparing result is not equal, then hide the desired menu div. Since we are trying to hide the menu div when clicking on any space beside the menu div, we will attach the click event target code to the document wrapper.
Here’s the code:
$(document).on("click", function (event) {
var $trigger = $(".toggledropdown"); // toggledropdown is the class of menu div.
if (!event.target.matches('.toggledropdown')) {
$('.toggledropdown').parent().removeClass('elemopen');
//".elemopen" class is for displaying the div. You can use your own show/hide code.
$('.toggledropdown').parent().parent().find('li').removeClass('elemopen');
}
});
JavaScript