Hey, so I have an event handler directly on a custom element in a template, for example:
html`
<custom-element @click=${(e) => console.log(e.target)}></custom-element>
`
My custom element has some children. The problem is that the target of the event is not the custom element itself, but one of the children. That's not intuitive to me, and actually I'm having a hard time figuring out a workaround. Is this how this behavior is supposed to work?
What about e.currentTarget?
Ah yes, that works...I suppose that's how it should work, no? e.target is the original node the event was generated from?
Correct, if you click on a child node, it will be the event's target, while the event's currentTarget will be the node the event was set on.
That's correct. target is the element that originally fired the event, and currentTarget is the current element in the event handling chain. Custom elements work the same as regular elements in that regard.
Consider this scenario:
<div id=clickable>
<span>Click me!</span>
</div>
If you attach a click handler to the div#clickable element, but you click on the span, the target of the event will be the span, not the div. If you want the element that the handler is attached to, you should use currentTarget. This article explains the differences: https://medium.com/@florenceliang/javascript-event-delegation-and-event-target-vs-event-currenttarget-c9680c3a46d1
There is only one special exception with Web Components; when an event crosses a ShadowDOM boundary, the target of the event becomes the shadowtree host. This is known as event retargeting, you can read some more about it here: https://developers.google.com/web/fundamentals/web-components/shadowdom#events
I appreciate the explanation, thanks!
Most helpful comment
That's correct.
targetis the element that originally fired the event, andcurrentTargetis the current element in the event handling chain. Custom elements work the same as regular elements in that regard.Consider this scenario:
If you attach a click handler to the
div#clickableelement, but you click on thespan, thetargetof the event will be the span, not the div. If you want the element that the handler is attached to, you should usecurrentTarget. This article explains the differences: https://medium.com/@florenceliang/javascript-event-delegation-and-event-target-vs-event-currenttarget-c9680c3a46d1There is only one special exception with Web Components; when an event crosses a ShadowDOM boundary, the
targetof the event becomes the shadowtree host. This is known as event retargeting, you can read some more about it here: https://developers.google.com/web/fundamentals/web-components/shadowdom#events