Making a dropdown menu disappear when clicking anything but the menu
I'm new to this site. I've googled for almost 6 days now for javascript to use in making a dropdown menu as seen on Google and Facebook. FB uses it on Account link. When开发者_StackOverflow you click on Account in Facebook, a dropdown menu comes out.
This is what I'd like:
When we click anywhere else on the page, it disappears, but it's still displayed when we click on this menu itself e.g. we can logout from the page, but if we click somewhere else, it disappears like some onblur event has occured.
I've written the code like the following:
<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 dropdown menu appears with all my details and disappears when I click it again. I want it to disappear when we click anywhere else on the page, which I'm unable to do.
If I use onblur then the dropdown menu disappears even when I click on it i. e. I can't use it.
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>
精彩评论