If you always want the element that the event listener is attached to, then access the currentTarget property on the event object, event.currentTarget, instead of event.target.
The currentTarget property is the element that the event listener is currently attached to (which in your case would be the div with the onclick attribute).
<div onclick="clickHandler(event)"></div>
function clickHandler(event) {
console.log('Event is attached to: ', event.currentTarget);
console.log('The element clicked was: ', event.target);
}
In addition, if you pass the this keyword as a parameter, it would also refer to that element as well. You can use the .call() method in order to set the value of this in the function callback.
Update your onclick attribute to the following:
<div onclick="clickHandler.call(this, event)"></div>
And then your function's this keyword would refer to that div element and event would be passed as the first parameter:
function clickHandler(event) {
console.log('Event is attached to: ', event.currentTarget);
console.log('The element clicked was: ', event.target);
console.log('"this" refers to: ', this);
}
Example demonstrating this:
div { border: 1px solid; height: 200px; width: 200px; }
<script>
function clickHandler(event) {
console.log('Event is attached to: ', event.currentTarget);
console.log('The element clicked was: ', event.target);
console.log('"this" refers to: ', this);
}
</script>
<div onclick="clickHandler.call(this, event)">
<span>'event.currentTarget' is the div</span>
<span>'this' is also the div</span>
</div>
Is there any way to stop the children from firing events?
You could check if event.target is event.currentTarget.
In the snippet below, the if statement will be true when clicking outside of the children elements and it will be false when clicking the children elements directly:
function clickHandler(event) {
if (event.target === event.currentTarget) {
// ...
}
}
Basic example:
div { border: 1px solid; height: 200px; width: 200px; }
<script>
function clickHandler(event) {
console.log(event.target === event.currentTarget);
}
</script>
<div onclick="clickHandler(event)">
<span>Click outside of a span</span>
<span>Another span</span>
</div>