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);
}());
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rafael Adel
  • 7,673
  • 25
  • 77
  • 118

1 Answers1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • actually, addEventListener is defined if window.addEventListener is defined. – kennebec Jul 21 '12 at 02: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 Jul 21 '12 at 04:14