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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With