tl;dr: Use event.currentTarget
unless you are absolutely certain that you need event.target
.
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
.