Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Illegal invocation on addEventListener

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.

like image 563
Artur Sapek Avatar asked Aug 27 '11 08:08

Artur Sapek


1 Answers

You need to wrap alert in a function. This will work:

ronan.addEventListener("click", function() { alert('Hi'); }, false);

Here's a fiddle for proof. Using alert alone doesn't work because when a listener is executed the value of this within that function is set to the object on which it is listening. For example, if you set a listener on ronan, within that listener this === ronan. This presents a problem for alert because that function expects this to be equal to window. You can work around this (no pun intended) by wrapping the function in another function or by binding it to whatever it expects this to be:

document.body.addEventListener('click', alert.bind(window), false);

Don't forget that in IE < 9 you need to use attachEvent rather than addEventListener.


A note on using apply/call with addEventListener

Your second attempt won't work because you're trying to apply your arguments to window.addEventListener, as opposed to HTMLElement.prototype.addEventListener, which is a different function altogether:

// This won't work
addEventListener.apply(ronan, ["click", alert.bind(window), false]);

// This will work
HTMLElement.prototype.addEventListener.apply(ronan, ['click', alert.bind(window), false]);
like image 85
Matthew Avatar answered Sep 24 '22 08:09

Matthew