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
});
Upvote for the most popular answer, but add
so, a click on a scroll bar does not [hide or whatever] your target element.
If you are scripting for IE and FF 3.* and you just want to know if the click occured within a certain box area, you could also use something like:
Instead using flow interruption, blur/focus event or any other tricky technics, simply match event flow with element's kinship:
To remove click outside event listener, simply:
If you click on the document, hide a given element, unless you click on that same element.
I did it like this in YUI 3:
I am checking if ancestor is not the widget element container,
if target is not which open the widget/element,
if widget/element I want to close is already open (not that important).
I have an application that works similarly to Eran's example, except I attach the click event to the body when I open the menu... Kinda like this:
More information on jQuery's
one()
function