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
});
I don't think what you really need is to close the menu when the user clicks outside; what you need is for the menu to close when the user clicks anywhere at all on the page. If you click on the menu, or off the menu it should close right?
Finding no satisfactory answers above prompted me to write this blog post the other day. For the more pedantic, there are a number of gotchas to take note of:
body { margin-left:auto; margin-right: auto; width:960px;}
As a variant:
It has no problem with stopping event propagation and better supports multiple menus on the same page where clicking on a second menu while a first is open will leave the first open in the stopPropagation solution.
This is my solution to this problem:
A simple solution for the situation is:
The above script will hide the
div
if outside of thediv
click event is triggered.You can see the following blog for more information : http://www.codecanal.com/detect-click-outside-div-using-javascript/
I've had success with something like this:
The logic is: when
#menuscontainer
is shown, bind a click handler to the body that hides#menuscontainer
only if the target (of the click) isn't a child of it.For easier use, and more expressive code, I created a jQuery plugin for this:
Note: target is the element the user actually clicked. But callback is still executed in the context of the original element, so you can utilize this as you'd expect in a jQuery callback.
Plugin:
By default, the click event listener is placed on the document. However, if you want to limit the event listener scope, you can pass in a jQuery object representing a parent level element that will be the top parent at which clicks will be listened to. This prevents unnecessary document level event listeners. Obviously, it won't work unless the parent element supplied is a parent of your initial element.
Use like so: