Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Get the element that triggered the event in an event handler function

A lot of people seem to get confused when trying to get the element that triggered the event in an event handler function. this or $(this) returns the parent element of the target.

Even before jQuery, vanilla JavaScript worked.

http://www.quirksmode.org/js/events_properties.html
JavaScript
function getTarget(e)
{
    var e = e || window.event, t;

    if (e.target) t = e.target;
    else if (e.srcElement) t = e.srcElement;

    if (t.nodeType == 3) // defeat Safari bug
    t = t.parentNode;

    return t;
}
JavaScript
Vanakkam !

0 comments: