0

I'm using this cross browser event handler function.

// crowss browsing event handler
var Event = {
    add: function(elem, type, handler) {
        if (elem.addEventListener) {
            elem.addEventListener(type, handler, false);
        } else if (elem.attachEvent) {
            elem.attachEvent("on" + type, handler);
        } else {
            elem["on" + type] = handler;
        }
    },

    remove: function(elem, type, handler) {
        if (elem.removeEventListener) {
            elem.removeEventListener(type, handler, false);
        } else if (elem.detachEvent) {
            elem.detachEvent("on" + type, handler);
        } else {
            elem["on" + type] = null;
        }
    },

    getEvent: function(event) {
        return event ? event : window.event;
    },

    getTarget: function(event) {
        return event.target || event.srcelem;
    },

    preventDefault: function(event) {
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
    },

    stopPropagation: function(event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        } else {
            event.cancelBubble = true;
        }
    }
}

Put this code in 'basicFunctions.js' and other codes are placed in the other file 'main.js'. And if I run the code, chrome displays this error message.

TypeError: Cannot read property 'addEventListener' of null
http://127.0.0.1/js/basicFunctions.js:4&host=127.0.0.1

I don't know the reason of this error.

What is the problem with this code???

This code was written on the book... And when I put this code in 'main.js' with other codes, there was no such error...

And I call this function like this :

Event.add(element,'click',function() {
});
goJson
  • 203
  • 2
  • 6
  • 12
  • 3
    How are you calling this code? – Niet the Dark Absol Sep 22 '14 at 16:18
  • 5
    Sounds like you are passing `null` to your function, not a reference to an element. See [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/q/14028959/218196) – Felix Kling Sep 22 '14 at 16:18
  • Kling, I don't understand what you are saying... that code worked fine when it was not separated with multiple files... – goJson Sep 22 '14 at 16:25
  • For example, a = document.getElementById('test'); Event.add(a,'click',function () { alert('asdf');}); – goJson Sep 22 '14 at 16:27
  • You can also create Namespaces in different pages, and return some methods over there. Try using this. – maddy Sep 22 '14 at 16:37

0 Answers0