Deleting a drop-down menu when you click on any menu except the menu

I am new to this site. I have been googled for almost 6 days now for javascript to use in creating a dropdown menu as seen on Google and Facebook. FB uses it under the Account link. When you click on “Facebook Account”, a drop-down menu will exit.

Here is what I would like:

When we click elsewhere on the page, it disappears, but it still appears when we click on this menu, for example. we can exit the page, but if we click elsewhere, it will disappear as soon as the onblur event occurs.

I wrote the code as follows:

<html> <head> <title>Untitled Document</title> <script type="text/javascript"> function dropdown() { var ele = document.getElementById("hide"); if(ele.style.display == "block") { ele.style.display = "none"; } else { ele.style.display = "block"; } } </script> </head> <body> <a href="#" onClick="dropdown()">Hello Mohd</a> <div id="hide" style="display:none"> <p>Hii All<p></p>Hw r u</p> <p><a href="#">Sign Out</a></p> </div> </body> </html> 

In the above code, it works well when I click the link. A popup menu appears with all my data and disappears when I click it again. I want it to disappear when we click elsewhere on the page, which I cannot do.

If I use onblur, the dropdown menu disappears even when I click on it. e. I cannot use it.

+4
source share
1 answer

Here you go:

http://jsfiddle.net/Paulpro/vty5s/

code:

 <html> <head> <title>Javascript Dropdown Example</title> <style type="text/css"> #hide{ display: none; background-color: #68D; border: 1px solid #000; width: 80px; } </style> <script type="text/javascript"> function showDropDown(e){ document.getElementById('test').onclick = function(){}; if(e.stopPropagation) e.stopPropagation(); // W3C model else e.cancelBubble = true; // IE model document.getElementById("hide").style.display = "block"; document.onclick = function(e){ var ele = document.elementFromPoint(e.clientX, e.clientY); if(ele == document.getElementById("test")){ hideDropDown(); return; } do{ if(ele == document.getElementById("hide")) return; }while(ele = ele.parentNode); hideDropDown(); }; } function hideDropDown(){ document.onclick = function(){}; document.getElementById("hide").style.display = "none"; document.getElementById('test').onclick = showDropDown; } </script> </head> <body> <a href="#" id="test">Hello Mohd</a> <div id="hide"> <p>Hii All<p></p>Hw r u</p> <p><a href="#">Sign Out</a></p> </div> </body> <script type="text/javascript"> document.getElementById('test').onclick = showDropDown; </script> </html> 
+4
source

All Articles