Would it be a bad idea to use a boolean to determine if child element was clicked or not? Is there any better method?
Note: I don’t want to use jquery for this.
See code below:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body{margin:0;}
#container{height:300px;background:red}
#box{width:500px;height:300px;background:blue;margin:auto}
</style>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
<script>
var hbWindow = window,
hbDocument = document,
hbBooleanIfIsOutside = new Boolean(),
hbIdBox = hbDocument.getElementById('box'),
hbIdContainer = hbDocument.getElementById('container');
hbWindow.onload = function () {
hbIdContainer.onclick = function () {
if(hbBooleanIfIsOutside) {
alert('you\'re outside!');
} else {
alert('you\'re inside!');
}
hbBooleanIfIsOutside = true;
}
hbIdBox.onclick = function () {
hbBooleanIfIsOutside = false;
}
}
</script>
</body>
</html>
Added new version:
In this version I am using addEventListener instead.
var hbWindow = window,
hbDocument = document,
hbIdBox = hbDocument.getElementById('box'),
hbIdContainer = hbDocument.getElementById('container');
hbWindow.onload = function () {
function inOrOut(e){
if (!e) e = hbWindow.event;
if((e.target || e.srcElement).id == 'container') {
alert('you\'re outside!');
} else {
alert('you\'re inside!');
}
}
hbIdContainer.addEventListener('click', inOrOut, false);
}
If you wish to know what invoked the click, check
event.target. On IE6-8 you would check thewindow.event.srcElementproperty.So while we’re attaching the event to the
document.body, we can determine by thetarget(or in some cases thesrcElement) which child triggered the click.Demo: http://jsbin.com/oxuzek/7/edit