1
oLink = document.getElementById("ItemDescend");
alert(oLink); // fire up alert with link target
addEventHandler(oLink, "click", function(e) { alert(1); sortTable('theList', 0, true); preventDefault(e); },false); // does not fire up inner alert!

This above code functions in all other browsers as tested, but in Chrome 12 does not. I would be grateful if someone shows me a solution. Thanks.

4
  • What is addEventHandler? You have to post the implementation, otherwise we cannot help. Commented Jul 6, 2011 at 2:52
  • function(oNode, sEvt, fnHandler, bCapture) { if (typeof (window.event) != "undefined") oNode.attachEvent("on" + sEvt, fnHandler); else oNode.addEventListener(sEvt, fnHandler, bCapture); }, Commented Jul 6, 2011 at 2:55
  • That is because Chrome does have window.event, but it does not have attachEvent. It would be better to check if oNode has attachEvent defined. Even better, use a framework that abstracts these details away. Commented Jul 6, 2011 at 2:59
  • But on window load event this function is working.. How is that possible? Commented Jul 6, 2011 at 3:03

2 Answers 2

1

Your addEventHandler method is checking for an unrelated property, which is wrong.

Instead, you should check for the addEventListener method, and only call attachEvent if that doesn't exist.
Change the condition to

if (typeof (oNode.addEventListener) !== "function")
Sign up to request clarification or add additional context in comments.

7 Comments

It is working for me: jsfiddle.net/nqmJf you may have a typo or some other issue.
addEventListener is a host method and may not return function when tested with typeof (e.g. in IE, methods implemented using ActiveX return "unknown"), so probably better to use if (oNode.addEventListener).
I am getting [Object HTMLDivElement] in jsfiddle.net/nqmJf, not 1. And would suggest you to make that div a link, just in case... I didnt try it...
@Rob: I was wondering about that. I had hoped that that was fixed by IE9, which is the only version with addEventListener.
@SLaks - IE may also return "object" and "other" for methods of host objects. I think the general rule is: don't depend on host objects implementing features of ECMAScript, code to the lowest common denominator (well, IE 6 and higher at least) :-)
|
1
addEventHandler(obj,type,fn)
{
    if(obj.addEventListener)
    {
        obj.addEventListener(type,fn,false);
    }
    else if (obj.attachEvent)
    {
        obj.attachEvent("on"+type,fn);
    }

}

1 Comment

Probably worth noting that when called, the listener's this will be set differently depending on which method was used to add it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.