How to detect click outside element?
P粉113938880
2023-08-23 13:37:35
<p>I have some HTML menus that I fully display when the user clicks on the header of these menus. I want to hide these elements when the user clicks outside the menu area. </p>
<p>Is this possible using jQuery? </p>
<pre class="brush:php;toolbar:false;">$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});</pre>
<p><br /></p>
You can listen to the
click
event on document and then make sure that the#menucontainer
is not an ancestor or target of the clicked element by using.closest()
.If not, the clicked element is outside the
#menucontainer
and you can safely hide it.Edited – June 23, 2017
You can also clean up after the event listener if you plan to close the menu and want to stop listening to events. This function will only clean up newly created listeners, leaving any other click listeners on
document
. Use ES2015 syntax:Edited – November 3, 2018
For those who don't want to use jQuery. This is the plain vanillaJS (ECMAScript6) code above.
Notice: This is based on Alex's comment, just use
!element.contains(event.target)
instead of the jQuery part.But
element.closest()
also now works in all major browsers (the W3C version is slightly different from the jQuery version). Polyfill can be found here: Element.closest()Edit – 2020-05-21
If you want the user to be able to click and drag inside an element and then release the mouse outside the element without closing the element:
In
outsideClickListener
:Attach a click event to the document body of the closed window. Attach a separate click event to the container to stop propagation to the document body.