Saturday, November 9, 2024

JavaScript Difference between target and currentTarget of Event

The target and currentTarget properties of an event object both refer to elements in the DOM, but they represent different things.
  • target refers to the element that triggered the event.
  • currentTarget refers to the element that the event listener is currently attached to.
Example:
Imagine you have the following HTML structure:
<div id="parent">
  <button id="child">Click Me!</button>
</div>
And the following JavaScript code:
document.getElementById('parent').addEventListener('click', function(event) {
    console.log('target:', event.target);         // Element that triggered the event
    console.log('currentTarget:', event.currentTarget); // Element the listener is attached to
});

document.getElementById('child').addEventListener('click', function(event) {
    console.log('target:', event.target);         // Element that triggered the event
    console.log('currentTarget:', event.currentTarget); // Element the listener is attached to
});

Behavior:
Clicking the child button:
  • target: This will refer to the button element (#child) because the button is the one that triggered the event.
  • currentTarget: In the case of the parent's event listener, currentTarget will refer to the div element (#parent) because the event listener was attached to the parent.
Output in the console:

target: <button id="child">Click Me!</button>
currentTarget: <div id="parent">...</div>
Clicking the parent div (outside the button):
  • target: This will refer to the div element (#parent) because the parent div is the one that triggered the event.
  • currentTarget: The currentTarget will still refer to the div element (#parent) because the event listener is attached to the parent.
Output in the console:
target: <div id="parent">...</div>
currentTarget: <div id="parent">...</div>

Summary:

  • target: The element that the event was directly dispatched to.
  • currentTarget: The element to which the event listener is currently attached.
This distinction is particularly useful in event delegation when you attach a single event listener to a parent element and need to handle events for multiple child elements.

No comments:

Post a Comment

Hot Topics