Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE8 onclick handler event

I've read most of the relevant articles in quirksmode.org but still I'm not sure about this one:

Making my app compatible with IE8 (fun fun fun) I encounter this issue when trying to set an onclick event to a link:

function myClickHandler(event)
{
    alert(event);
}

var link = document.getElementById("myLink");
link.onclick = myClickHandler; //first option

As opposed to:

function myClickHandler(event)
{
    alert(event);
}

var link = document.getElementById("myLink");
link.onclick = function() {
   myClickHandler(event); //second option
}

Using the first option, myClickHandler alerts undefined. Using the second option alerts [object Event] which makes me believe that the event object isn't passed by the first option to the handler. Why is this so on IE8?

Note: Don't want to use attachEvent as I want to override a single listener during execution and onclick seems to fit here fine.

like image 217
user1555863 Avatar asked Aug 19 '13 08:08

user1555863


1 Answers

Yes, the event object is not passed as a parameter to DOM0-style event handlers in IE <= 8. You need to get it from window.event instead. If you add a parameter called event, in IE <= 8 this will be undefined and references to event within the event handler will resolve to the undefined parameter rather than window.event. I usually use window.event to make this explicit in the code:

link.onclick = function(evt) {
   evt = evt || window.event;
}
like image 154
Tim Down Avatar answered Oct 09 '22 17:10

Tim Down