AddEventListener not working in Chrome

I follow the Lynda.com tutorial about the new DOM event model.

This is the code I'm working with.

function addEventHandler(oNode, sEvt, fFunc, bCapture){ if (typeof (window.event) != "undefined") oNode.attachEvent("on" + sEvt, fFunc); else oNode.addEventListener(sEvt, fFunc, bCapture); } function onLinkClicked(e){ alert('You clicked the link'); } function setUpClickHandler(){ addEventHandler(document.getElementById("clickLink"), "click", onLinkClicked, false); } addEventHandler(window, "load", setUpClickHandler, false); 

I add it to the click event by this link

 <a href="#" title="click me" id="clickLink">Click Me!</a> 

It works fine in IE, Firefox, Opra, but not in Chrome. I looked around, but so far I could not find anything concrete. Some similar questions, but this does not answer my question.

I get the following error from the Chrome console

 Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'attachEvent' 

any sugestions or link to answer.

Thanks in advance.

+7
source share
1 answer

Why are you testing:

 if (typeof (window.event) != "undefined") 

... to decide whether to use attachEvent() ? Chrome defines window.event , so your code is trying to use attachEvent() , which is not defined.

Try directly testing the method instead:

 if (oNode.attachEvent) oNode.attachEvent("on" + sEvt, fFunc); else oNode.addEventListener(sEvt, fFunc, bCapture); 
+7
source

All Articles