Front-end education for the real world. Since 2018.





Event currentTarget to the rescue

Andy Bell

Topic: JavaScript

If you’ve attached an event to an element and queried the event target inside its event handler, you’ve probably found that if there are child elements, they can end up being the event target.

I’m talking about this sort of thing:

Code language
html

<button>
  <span>A label</span>
  <svg><!-- Icon --></svg>
</button>

Code language
js

document.querySelector('button').addEventListener(evt => {
  console.log(evt.target);
});

The problem is, you might have some data attributes on the button itself that you want to access like this:

Code language
html

<button data-something="hello">
  <span>A label</span>
  <svg><!-- Icon --></svg>
</button>

Code language
js

document.querySelector('button').addEventListener(evt => {
  console.log(evt.target.getAttribute('data-something'));
});

If the pointer, or a person’s finger hits the <svg> or the <span>, you won’t get access to data-something and at after lots of debugging and head scratching, you might be tempted to throw your computer out of the window.

Step up currentTargetpermalink

There is a solution, though: currentTarget! This will always refer to the element which you attached the event to, so update your JS code to look like this instead:

Code language
js

document.querySelector('button').addEventListener(evt => {
  console.log(evt.currentTarget.getAttribute('data-something'));
});

Wrapping uppermalink

Was this post written after I spent an embarrassing amount of time debugging some JavaScript? Yes.

Will it help you not do the same in the future? I really hope so…

Enjoyed this article? You can support us by leaving a tip via Open Collective


Newsletter