javascriptcross-browserdom-eventsbrowser-feature-detection

Feature detection is not working for events in Internet Explorer


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);
}());

Solution

  • 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.