• support@answerspoint.com

How to detect a click outside an element?

2133

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
});

2Answer


0

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

0

You can hook up to the click event of document and then make sure #menucontainer is not an ancestor or the target of the clicked element (jQuery.closest(), jQuery.is()).

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 && !$(event.target).is('#menucontainer')) {
        if($('#menucontainer').is(":visible")) {
            $('#menucontainer').hide()
        }
    }        
})
  • answered 8 years ago
  • G John

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2133 times
  • active 9 years ago

Best Rated Questions