I’m attempting to create a javascript where when you click anywhere on the screen but on an object, it does a bit of code. (To close a dialogue box, remove nighttime mode, etc.)
//Imagine some CSS declaring that FPAGE takes up 100% of the screen.
<div id="FPAGE" onclick="return outClick();">
<script>
function outClick() {
var o=document.getElementsByClassName('objects');
//What now?
}
</script>
<center>
<object class="objects" width="500px" height="500px"></object>
<br />
<object class="objects" width="500px" height="500px"></object>
</center>
</div>
I’m really unsure what I should be doing. I have thought of some sudo code, but I don’t know if this can be done in javascript.
var o=document.getElementsByClassName('objects');
//What now?
if (onclick!=o) {
//insert code here
}
SOLUTION: (Thanks to David)
<script>
document.onclick = function(e) {
var o=document.getElementsByClassName('objects');
if ( e.target.nodeName != 'o' ) {
//Code here!
}
};
</script>
<center>
<object class="objects" width="500px" height="500px"></object>
<br />
<object class="objects" width="500px" height="500px"></object>
</center>
</div>
You could add a click event on the entire page, then check whether the target of that click was the object (or perhaps a descendant of that object). Something like this:
Demo: http://jsbin.com/elikum/1
Remember that javascript events are difficult to normalize in legacy browsers, so depending on the target audience you might consider a library like jQuery to make event handling easier.