In JavaScript, the main difference between Event.target and Event.currentTarget properties is that:
targetrefers to the element that triggered the event;currentTargetrefers to the element that the event handler/listener is attached to.
For example:
<div id="target">
<span>click me</span>
</div>
const elem = document.getElementById('target'); // div
elem.addEventListener('click', function (event) {
console.log(event.target); // span
console.log(event.currentTarget); // div
});
As you can see from the example above, when you click on the <span> element, the currentTarget would refer to the element that the event handler is attached to (i.e. <div>), and the target would refer to the element that triggered the event (i.e. <span>).
In the following example, the target and the currentTarget are going to be the same elements because the element that triggers the event, and the element that the event handler is attached to, are the same:
<div>
<span id="target">click me</span>
</div>
const elem = document.getElementById('target'); // span
elem.addEventListener('click', function (event) {
console.log(event.target); // span
console.log(event.currentTarget); // span
});
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.