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

<p>NOTE: Using <code>stopEventPropagation()</code> is something that should be avoided as it breaks normal event flow in the DOM. See <a href=”” rel=”noreferrer”>this article</a> for more information. Consider using <a href=”″>this method</a> instead.</p>
<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


<div class=”source-button clearfix”>
<a class=”button source-button” href=”” target=”_blank” rel=”noopener”>Source</a>