I use this code which opens and closes a menu. How can I have it close when someone clicks anyplace on the screen?
function showElement(layer){
var myLayer = document.getElementById(layer);
if(myLayer.style.display=="none"){
myLayer.style.display="block";
myLayer.backgroundPosition="top";
} else {
myLayer.style.display="none";
}
}
The HTML
<div style="float:left;">
<a href="#" class="button" onclick="javascript:showElement('v-menu')">
<span>Monitoring</span></a>
<ul id="v-menu" class="v-menu" style="display:none;" >
<li><a href="#" onclick="javascript:showElement('v-menu')">Start</a></li>
<li><a href="#">Stop</a></li>
</div>
You will need to do two things to achieve this:
Bind a click event for the whole document, and hide the menu if it is shown.
Stop the click event propagation when the menu is clicked, so the event does not bubble up to the document.
See this in action: http://jsfiddle.net/william/Pfv8N/.