Floris Floris - 2 months ago 10x
Javascript Question

Event target should be anchor but is image instead

I am working on a dialog script in Vanilla JS. I ran into a problem with the click event on the video image. Even tough the image is surrounded with an anchor tag it shows the image as the event.target on the "trigger-dialog-open" event.

Here is the HMTL:

<a class="trigger-dialog--open thumbnail" data-dialog-id="dialog-video" href="javascript:;">
<img src="http://i.ytimg.com/vi/id/sddefault.jpg" alt="" />

And this is the event in JS:

var openTriggers = document.getElementsByClassName('trigger-dialog--open');
for (var i = 0; i < openTriggers.length; i++) {
openTriggers[i].addEventListener("click", function (event) {
}.bind(this), false);

The event handler wants to know the dialog-id from the anchors data attribute. It can't be found because it thinks the image is the event.target, not the actual anchor. How can I correct this? Thanks!


Use event.currentTarget. The event.target is supposed to be the img element since that is what the user has clicked on. The click then bubbles up through the image's containers. event.currentTarget gives you the element that the click handler was actually bound to.

(Or if you didn't bind this to some other object you could use this within the click handler and it should also be the current target.)