Muhammad Muhammad - 8 months ago 26
Javascript Question

Collapse a menu when clicked outside the menu, but keep it open when clicked inside

I am trying to create a popup menu with JQuery. This menu shows when a certain element is clicked, and of course, when the same element is clicked again, it collapses.
Now what I want, is that after this menu has been opened up, when the user clicks anywhere on the web page, the menu should close. I am using the following code to accomplish this.




What is happening now, is that when the user clicks anywhere on the web page, including the menu it-self, the menu closes down. So even if you tried to access the sub-menu inside the (#div-header-submeu), it would open the sub menu, but it will collapse the main menu.

Any ideas how to fix this situation? Just to re-iterate, I need the #div-header-submenu to remain open when clicked inside the main menu, but collapse, if clicked anywhere outside.

Here is the Fiddle complete markup of the menu



Hy, @Dhaval Chhenda answer should work. Another way of thinking is to wrap all the page content in a

<div id="main">...</div> <menu>...</menu>

with you menu outside of it. And then call the on('click') method on main tag as shown here :

that will give you something like

html :

<body> <div id=main> Content </div> <menu> menu </menu> </body>


$( "#main" ).click(function() { $('#div-header-submenu').collapse('hide'); });


menu { z-index: 100; }

z-index should be topped to be sure that it's on top of the layout.

Hope it will help you :)