Reputation: 2464
I have a Javascript event handler that is not getting me the attributes I need. Here is my situation.
I have an HMTL DOM similar to the following:
<div id='section-header'>
<a href="#anchor1">
<img src="path/to/an/image1.png">
</a>
<a href="#anchor2">
<img src="path/to/an/image2.png">
</a>
</div>
I am instantiating my event listener like so:
var aList = document.getElementById('section-header').getElementsByTagName('a');
var anchorScroll = (event) => {
event.preventDefault();
var target = event.target.attributes;
console.log("target: ", target);
};
for (var i = 0;i < aList.length;i++) {
aList[i].addEventListener('click', anchorScroll, false);
}
When I click on one of the images, the event function is fired, however the target element is the image, not the a
tag. Thus, the attributes
object does not have an href
key-value pair, and I need that href
. Instead, the attributes object only has an src
key-value pair.
Why is the a
element not the target of this event? How do I remedy this?
Upvotes: 0
Views: 1956
Reputation: 9782
You can use event delegation to capture all the clicks within section-header, then determine what action to take based on the tag name.
var anchorScroll = (event) => {
var link;
event.preventDefault();
if (event.target.tagName === 'IMG') {
link = event.target.parentNode;
} else {
link = event.target;
}
console.log("target: " + link);
};
document.getElementById('section-header').addEventListener('click', anchorScroll);
<div id='section-header'>
<a href="#anchor1">
<img src="path/to/an/image1.png">
</a>
<a href="#anchor2">
<img src="path/to/an/image2.png">
</a>
</div>
<div id="output"></div>
Upvotes: 1
Reputation: 522042
Yes, the initial target of the event will be the img
, since it's the innermost element that was clicked on. To distinguish between it and the element the event handler is actually bound to, the Event
object has both target
and currentTarget
properties:
(
currentTarget
) [i]dentifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed toevent.target
which identifies the element on which the event occurred.https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
Or you may simply use this
instead.
Upvotes: 5