• support@answerspoint.com

How to detect a click outside an element?

2080

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 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

    Facebook Share        
       
  • asked 8 years ago
  • viewed 2080 times
  • active 8 years ago

Best Rated Questions