Event currentTarget to the rescue

Categories

A really quick tip to hopefully save you from throwing your computer out of the window due to JavaScript events.


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 currentTarget permalink

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 up permalink

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…

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.