I get an Uncaught TypeError: Illegal invocation for both versions of this attempt to put down an EventListener: (I get the error when the listener should be added, not when I click on the target)
ronan.addEventListener("click", alert, false);
addEventListener.apply(ronan, ["click", alert, false]);
ronan is a div element that is returned successfully by the console so I don’t think that’s the problem. Any ideas why I get this error? I read this thread and I couldn’t figure it out from that.
You need to wrap
alertin a function. This will work:Here’s a fiddle for proof. Using
alertalone doesn’t work because when a listener is executed the value ofthiswithin that function is set to the object on which it is listening. For example, if you set a listener onronan, within that listenerthis === ronan. This presents a problem foralertbecause that function expectsthisto be equal towindow. You can work around this (no pun intended) by wrapping the function in another function or by binding it to whatever it expectsthisto be:Don’t forget that in IE < 9 you need to use
attachEventrather thanaddEventListener.A note on using
apply/callwithaddEventListenerYour second attempt won’t work because you’re trying to apply your arguments to
window.addEventListener, as opposed toHTMLElement.prototype.addEventListener, which is a different function altogether: