Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I guaranteed to get an event object with a target property in a JavaScript event handler?

Just as the title says I'm curious if I'm guaranteed to get an event object inside of a JavaScript event handler. The main reason I'm asking is that I've seen onClick event handlers that look like this:

function(e) {
    if(e && e.target) {
        //Code in here
    }
}

Which seems wrong to me, but I know JavaScript can have minor variances across browsers. Is there some time at which it's appropriate to check for the event object? Or the event target? It seems like you'd have to have a target to fire off an event.

like image 280
Jazzepi Avatar asked Jan 19 '26 11:01

Jazzepi


1 Answers

No. Older versions of windows don't pass the event argument to the event handler. They have it in a global variable window.eventand the target is in .srcElement. Other than that exception, you should always get an event structure.

A work-around for the older versions of IE is this:

function(e) {
    if (!e) {
        e = window.event;
        e.target = e.srcElement;
    }
    // code that uses e here
}

But, usually, this is addressed at a higher level by the function that you use to install event handlers. For example:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            window.event.target = window.event.srcElement;
            return(fn.call(elem, window.event));   
        });
    }
}
like image 79
jfriend00 Avatar answered Jan 21 '26 01:01

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!