DEV Community

Amandeep Kochhar
Amandeep Kochhar

Posted on

[JavaScript] -event.Target vs event.currentTarget

event.target Points to element, which triggers the event.

event.currentTarget Points to element, to which the Event Listener is attached to.

Confused?

Let's consider this example, where a button is nested inside a paragraph and both button and paragraph having click event.

<p id="paragraph">
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero,
  aliquid? <br />
  <button id="btn">Click Me</button>
</p>
Enter fullscreen mode Exit fullscreen mode
document.getElementById("paragraph").addEventListener("click", 
  function (event) {
    console.log(
    `Target = ${event.target.tagName},
     Current Target = ${event.currentTarget.tagName}`
    );
});

document.getElementById("btn").addEventListener("click", 
  function (event) {
    console.log(
    `Target = ${event.target.tagName}, 
     Current Target = ${event.currentTarget.tagName}`
    );
});
Enter fullscreen mode Exit fullscreen mode

When we click on the paragraph the event.target and event.currentTarget points to the same element i.e paragraph. Because, element which triggers the event and element where event listener is attached are the same.

Now, what happens when we click on the Button, Click listener of the button get executed, event.target and event.currentTarget for this button again remains same.

But

Event also bubbled up to the parent element i.e Paragraph, Here the scenario is like this.

event.target points to the Button since button is the one who triggers the click event, but event.currentTarget points to the Paragraph and not button, since paragraph is the one where event listener is attached to.

Hoping now the difference between the event.target and event.currentTarget is cleared.

Cheers!

Top comments (0)