Read more

JavaScript events: target vs currentTarget

Arne Hartherz
July 24, 2015Software engineer at makandra GmbH

tl;dr: Use event.currentTarget unless you are absolutely certain that you need event.target.


Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Since it hasn't been written down in this deck before, here it goes:

When working with JavaScript Event objects, the DOM element that triggered the event is attached to them. [1]
However, there are 2 "opinions" on which element that would be:

  • The element that the user interacted with (event.target),
  • or the element that the event listener is bound to (event.currentTarget).

Note that both can be, but not necessarily are the same element.

Example

<button onclick="...">
  <strong>Delete</strong> user
</button>

When a user just clicks the word "user" inside the button, both event.target and event.currentTarget refer to the <button> element.

However, if they click the word "Delete", event.target will be the <strong> element, while event.currentTarget still refers to the <button>.

See http://jsfiddle.net/1hopz5o2/ Show archive.org snapshot for a demo.

Note about event delegation

When using event delegation, jQuery will set event.currentTarget to the element that was matching your selector.

In the example above:

$(document).on('click', 'button')

If the user clicks the word "Delete", event.target will be the <strong> element, while event.currentTarget still refers to the <button>.

If you wanted to get document, you need to call event.delegateTarget.

Rule of thumb

Use event.currentTarget.
When binding event callbacks, you usually want to do things with the element they are bound to.


[1] Note that some MouseEvents also have other targets Show archive.org snapshot .

Posted by Arne Hartherz to makandra dev (2015-07-24 10:55)