Javascript: Click anywhere in body except the one element inside it
You need to stopPropagation
to the outer element.
Here's a simple illustration: http://jsfiddle.net/5mhqrhwk/3/
var body = document.getElementById('wrapper');
var except = document.getElementById('except');
body.addEventListener("click", function () {
alert("wrapper");
}, false);
except.addEventListener("click", function (ev) {
alert("except");
ev.stopPropagation(); //this is important! If removed, you'll get both alerts
}, false);
HTML:
<div id="wrapper">
<center>
<div id="except"></div>
</center>
</div>
You don't really need any flags to do this. Just listen on body click and do different thing depending on the item clicked (event.target). This code should do exactly what you wanted (based on your code):
var body = document.getElementById('wrapper');
var except = document.getElementById('except');
if(body.addEventListener)
body.addEventListener("click", bodyClick, false);
else
body.attachEvent("onclick", bodyClick);
function bodyClick(event){
if(event.target != except)
except.style.display = "none";
}