Reputation: 3763
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);
}
Upvotes: 1
Views: 205
Reputation: 268344
If you wish to know what invoked the click, check event.target
. On IE6-8 you would check the window.event.srcElement
property.
if ( document.body.addEventListener ) {
document.body.addEventListener("click", alertMe, false);
} else if ( document.body.attachEvent ) {
document.body.attachEvent("onclick", alertMe);
}
function alertMe(event) {
console.log( event.target || window.event.srcElement.nodeName );
}
So while we're attaching the event to the document.body
, we can determine by the target
(or in some cases the srcElement
) which child triggered the click.
Demo: http://jsbin.com/oxuzek/7/edit
Upvotes: 1