"wrong" event target in handler

I have a snippet that looks like this:

<div data-item-url="..." data-action="click->delete#ask">
  <span class="icon has-text-danger">
    <i class="far fa-trash-alt"></i>
  </span>
</div>

“ask” is obviously a handler in my controller and the i-tag is expanded into a fontawesome icon. If I click on the icon, my handler is called as I would expect. But the target of the event is not the div. It is some generated SVG of the icon.

I’m a bit confused, because I don’t connect any click events to the SVG. I would expect that the div is the target of the event. I found another answer which proposes to use currentTarget instead of target, but that one is null. When looking at the event via dev tools, I only see SVG elements, but not my div.

Am I missing something? I need to access data-item-url in my handler and I don’t see how to do that with the wrong event target.

That’s the correct approach:

event.currentTarget: The target on which the event listener is installed (either the element with the data-action attribute, or document or window)
https://stimulusjs.org/reference/actions#event-objects

event.currentTarget shouldn’t be null. If you’re determining that with console.log(event), try console.log(event.currentTarget) instead.

1 Like

Adding a bit more to @javan’s response, the target will be the element that triggered the event, which in this case is the icon. In Javascript, events “bubble” up through the DOM. So in this case, the icon triggers the event, and that event bubbles up to <span>, which has no event handler, and then up to <div> which does have an event handler and responds to the event. The element with the event handler (the <div> in this case) is the currentTarget.

It’s unclear why the event.currentTarget would be null. Including your ask() function may help us diagnose here.

Mozilla’s docs go more in depth on events and bubbling:


1 Like

Thanks for your answers, which are perfectly correct. I was using target which is wrong. While debugging, I checked currentTarget in the Firefox console. There it is displayed as null, but it isn’t. I stumbled upon this in a blog post and it seems to be a general “display issue” in the Firefox console (in some situations?). Now I’m using currentTarget and everything works as expected. Thanks for your help!