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
});
After research I have found three working solutions (I forgot the page links for reference)
First solution
Second solution
Third solution
As another poster said there are a lot of gotchas, especially if the element you are displaying (in this case a menu) has interactive elements. I've found the following method to be fairly robust:
Solution1
Instead of using event.stopPropagation() which can have some side affects, just define a simple flag variable and add one
if
condition. I tested this and worked properly without any side affects of stopPropagation:Solution2
With just a simple
if
condition:Hook a click event listener on the document. Inside the event listener, you can look at the event object, in particular, the event.target to see what element was clicked:
I ended up doing something like this:
I have a close button within the new container for end users friendly UI purposes. I had to use return false in order to not go through. Of course, having an A HREF on there to take you somewhere would be nice, or you could call some ajax stuff instead. Either way, it works ok for me. Just what I wanted.
Works for me just fine.