Clicking on elements in jQuery causes bubble up to body. If we have a click handler binded to body that shows an alert, then clicking on any element will bubble up to body and trigger the alert. My Question is, is there any way to know if the body alert was triggered as a result of direct click to body, or was the click triggered because of a bubble up to body.
-
1Whatever you do, be wary of stopPropagation. That will break all `.live` calls. – Stefan Kendall May 19 '11 at 18:23
5 Answers
Compare event.target
to this
. this
is always the event where the handler is bound; event.target
is always the element where the event originated.
$(document.body).click(function(event) {
if (event.target == this) {
// event was triggered on the body
}
});
In the case of elements you know to be unique in a document (basically, just body
) you can also check the nodeName
of this
:
$(document.body).click(function(event) {
if (event.target.nodeName.toLowerCase() === 'body') {
// event was triggered on the body
}
});
You have to do toLowerCase()
because the case of nodeName
is inconsistent across browsers.
One last option is to compare to an ID if your element has one, because these also have to be unique:
$('#foo').click(function(event) {
if (event.target.id === 'foo') {
// event was triggered on #foo
}
});

- 233,373
- 50
- 316
- 318
You can check what was clicked with event.target
:
$(something).click(function(e){
alert(e.target)
})

- 144,921
- 39
- 244
- 303
In React, we can directly get using currentTarget and target
import React from "react";
function Bar() {
return (
<div
onClick={(ev) => {
if (ev.target == ev.currentTarget) console.log("Target hit");
}}
>
Click me, maybe <div>test doesnt trigger hit</div>
</div>
);
}

- 1,956
- 3
- 13
- 23
The "event" parameter passed to the handler has a "target" property, which refers to the element that was the direct target of the event. You can check that property to see if it's the <body>
element.
Note that the jQuery ".delegate()" facility can be used to do that checking for you.

- 405,095
- 59
- 585
- 614
In React, you need to create a reference to the Component with React.createRef(). Something like this:
class Foo extends React.Component {
constructor(props) {
super(props);
this.eRef = React.createRef();
}
render() {
return(
<div
ref={this.eRef}
onClick={(ev) => {
if (ev.target == this.eRef.current) console.log("Target hit");
}}
>
Click me, maybe
</div>
);
}
}

- 13,677
- 5
- 47
- 65