I have a page with a number of divs in it and when someone clicks one of them it calls a javascript method. I need to be able to also trigger another method call if someone clicks the body, meaning they didn't click a div but outside the div. When I put a jquery click handler on the body tag it fires even when you click the div. Anyone know how I can restrict the click to anything outside the divs? Thanks.
Asked
Active
Viewed 824 times
1
-
I'd imagine somwhere in the click event will be a reference to the element which 'was underneath' at the time, often this is the 'target' if you can get a handle on that it should be pretty simple to perform a conditional check to find out if it was a div, or the html body element. – dougajmcdonald Feb 09 '12 at 14:51
-
possible duplicate of [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – Jamiec Feb 09 '12 at 14:52
-
Thank you everyone. I was able to use the jquery target id to see if it's the body. That worked great. – geoff swartz Feb 09 '12 at 15:13
-
selector: `body :not(*)` – noob Feb 09 '12 at 15:17
3 Answers
1
You need to check the original target of the click event. It is accessible as e.target
where e
is the click event.
var div = document.getElementById('the-div');
document.body.onclick = function (e) {
var target = e.target;
while (target !== document.body) {
if (target === div) {
// The user clicked inside the div
return;
}
target = target.parentNode;
}
// do the stuff you want when they click outside the div here
};

J. K.
- 8,268
- 1
- 36
- 35
0
You can set the onclick
callback on the whole document:
document.onclick = function(){
alert("CLICK");
};
See also JavaScript event delegation

Mariusz Jamro
- 30,615
- 24
- 120
- 162
-1
You could make the entire window track click events, where the div, if clicked, will stop event propagation.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#wrapper {
position:absolute;
left:0px;
top:0px;
width:100%;
height:100%;
}
#antidiv {
position:absolute;
left:40px;
top:80px;
width:100px;
height:100px;
background-color:#3FF;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="antidiv"></div>
</div>
<script>
document.getElementById("antidiv").addEventListener("click", function(e) {
e.stopPropagation();
}, false);
document.body.addEventListener("click", function(e) {
alert("You didn't click the div!");
}, false);
</script>
</body>
</html>

Jeffrey Sweeney
- 5,986
- 5
- 24
- 32
-
-
Why not? :) I'll look in to JSFiddle for future responses though. – Jeffrey Sweeney Feb 09 '12 at 15:11
-