0

I'm trying to write a cross-browser event addition method but it's not working in IE at all, here's the code :

index.html

<!doctype html>
<html>
    <head>
    </head>

    <body>            
        <script type="text/javascript" src="helper.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </body>

</html>

helper.js

var eventUtil = {

    add : function(el, type, fn){
        if(typeof(addEventListener) !== "undefined"){
            el.addEventListener(type, fn, false);
        } else if (typeof(attachEvent) !== "undefined"){
            el.attachEvent("on"+type, fn);  
        } else {
            el["on"+type] = fn;
        }
    }    
}

script.js

(function(){
    var printMsg= function(){            
        document.write("hello");
    };
    eventUtil.add(document.body, "click" , printMsg);
}());

1 Answer 1

2

You need to do:

add : function(el, type, fn){
    if(typeof(el.addEventListener) !== "undefined"){
        el.addEventListener(type, fn, false);
    } else if (typeof(el.attachEvent) !== "undefined"){
        el.attachEvent("on"+type, fn);  
    } else {
        el["on"+type] = fn;
    }

As you had it with:

    if(typeof(addEventListener) !== "undefined"){

that will always be undefined as addEventListener is not a global variable/function it's a method on the element.

2
  • actually, addEventListener is defined if window.addEventListener is defined.
    – kennebec
    Commented Jul 21, 2012 at 2:44
  • @kennebec - that is no different than what I said - I'm not sure what new information you're adding. window.addEventListener is the same as a global variable/function named addEventListener because the global javascript namespace in a browser is window.
    – jfriend00
    Commented Jul 21, 2012 at 4:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.