IE event callback object JavaScript

Posted by Randy Hall on Stack Overflow See other posts from Stack Overflow or by Randy Hall
Published on 2012-11-20T15:50:43Z Indexed on 2012/11/20 17:00 UTC
Read the original article Hit count: 279

I may be WAY off on my terminology, so please feel free to correct me. Perhaps this is why I cannot seem to find anything relevant. No libraries, please.

I have an event handler, which invokes a callback function. Fancy, right? In IE<9 the this object in the handler is the window. I don't know why, or how to access the correct object.

if (document.addEventListener){
    element.addEventListener(event, callback, false);
} else {
    element.attachEvent('on' +event, callback);
}

This part DOES WORK.

This part doesn't:

function callback(event){
    console.log(this);
}

this in IE is returning [object Window], whereas it returns the element that called the callback function in every other browser. This is cut down significantly from my full script, but this should be everything that's relevant.

EDIT

This link provided by @metadings How to reference the caller object ("this") using attachEvent is very close. However, there are still two issues.

1) I need to get both the event object and the DOM element calling this function.

2) This event is handled delegation style: there may be child DOM elements firing the event, meaning event.target is not necessarily (and in my case, not typically) the element with the listener.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about internet-explorer