Look this code:
<div>
<a href = "#"><span>Click me MAN !</span></a>
</div>
<script type = "text/javascript">
window.onload = function () {
document.body.addEventListener ("click", function (event) {
var target = event.target;
alert ("Returns \"" + target.nodeName + "\". Just want \"" + target.parentNode.nodeName + "\"")
}, false);
}
</script>
You can see the element "span" inside a "link", when the "link" is clicked the current target is the same "span". How can the "event.target" return "link" instead of "span".
Thanks and no, I don't want to use "parentNode".
currentTarget is the element to which the event is attached. It will never change. Event. target is the element that triggered the event.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.
Definition and Usage. The event. target property returns which DOM element triggered the event. It is often useful to compare event. target to this in order to determine if the event is being handled due to event bubbling.
With your approach, you either have to manually traverse up the DOM until you hit an <a>
element or attach the listener to the link itself and use this
.
Minimizing the number of event listeners is generally a good idea, so here's an example of how to traverse the DOM. Note that the event listener will not work in IE, which does not support the addEventListener()
method of DOM nodes.
Live example: http://jsfiddle.net/timdown/pJp4J/
function getAncestor(node, tagName) {
tagName = tagName.toUpperCase();
while (node) {
if (node.nodeType == 1 && node.nodeName == tagName) {
return node;
}
node = node.parentNode;
}
return null;
}
document.body.addEventListener("click", function(event) {
var target = getAncestor(event.target, "a");
if (target !== null) {
alert(target.nodeName);
}
}, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With