DEV Community

Amandeep Kochhar
Amandeep Kochhar

Posted on

3 1

[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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay