snippetjavascriptCritical
How do I detect a click outside an element?
Viewed 0 times
howdetectelementoutsideclick
Problem
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.
Is something like this possible with jQuery?
Is something like this possible with jQuery?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});Solution
Note: Using
Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
stopPropagation is something that should be avoided as it breaks normal event flow in the DOM. See this CSS Tricks article for more information. Consider using this method instead.Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
Context
Stack Overflow Q#152975, score: 2027
Revisions (0)
No revisions yet.