How to detect a click outside an element?
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?
$("#menuscontainer").clickOutsideThisElement(function() {
// hide the menus
});
Javascript
jQuery
- asked 9 years ago
- B Butts
2Answer
Attach a click event to the document body which closes the window. Attach a separate click event to the window which stops propagation to the document body.
$('html').click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
Warning, if using this technique, be aware of the dangers of stopping propagation.
- answered 8 years ago
- Sunny Solu
You can hook up to the click event of document and then make sure #menucontainer
is not an ancestor of the clicked element (jQuery.closest()).
If it is not, then the clicked element is outside of the #menucontainer
and you can safely hide it.
$(document).click(function(event) {
if(!$(event.target).closest('#menucontainer').length) {
if($('#menucontainer').is(":visible")) {
$('#menucontainer').hide()
}
}
})
Hope it helps.
- answered 8 years ago
- G John
Your Answer