• support@answerspoint.com

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



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


Warning, if using this technique, be aware of the dangers of stopping propagation.

  • answered 7 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")) {

Hope it helps.

  • answered 7 years ago
  • G John

Your Answer

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

Best Rated Questions