Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target on click

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".

like image 639
Caio Avatar asked Jan 10 '11 00:01

Caio


People also ask

What is the difference between target and currentTarget?

currentTarget is the element to which the event is attached. It will never change. Event. target is the element that triggered the event.

What is the event target when clicking the button?

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.

What is the type of event target?

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.

What is E target jQuery?

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.


1 Answers

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);
like image 170
Tim Down Avatar answered Sep 27 '22 18:09

Tim Down