How do I detect a click outside an element?

 

<p>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.</p>
<p>Is something like this possible with jQuery?</p>
<pre><code>$(“#menuscontainer”).clickOutsideThisElement(function() {
// Hide the menus
});
</code></pre>
<hr />

<blockquote>
<p>NOTE: Using <code>stopEventPropagation()</code> is something that should be avoided as it breaks normal event flow in the DOM. See <a href=”https://css-tricks.com/dangers-stopping-event-propagation/” rel=”noreferrer”>this article</a> for more information. Consider using <a href=”https://stackoverflow.com/a/3028037/561309″>this method</a> instead.</p>
</blockquote>
<p>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.</p>
<pre><code>$(window).click(function() {
//Hide the menus if visible
});

$(‘#menucontainer’).click(function(event){
event.stopPropagation();
});
</code></pre>

&nbsp;
&nbsp;
<div class=”source-button clearfix”>
<a class=”button source-button” href=”https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element” target=”_blank” rel=”noopener”>Source</a>
</div>