Skip to content Skip to sidebar Skip to footer

Addeventlistener Code Snippet Translation And Usage For Cross-browser Detectioin

I've come across a piece of code that I'd like to model. However, I just have a few questions and perhaps you guys can help. Here's the code: function addEvent( brw_obj, type, func

Solution 1:

I have been using the try/catch approach for a while and it's been working just fine for my current projects. Please have a look at the following code snippet:

var request;

try {
    request = new XMLHttpRequest(); // standard
}
catch (e) {
    request = new ActiveXObject("Microsoft.XMLHTTP"); // workaround
}

The above sample should work on all browsers back to Internet Explorer 5.0; Of course, you can't support all ancient browsers, but hey, Mosaic didn't talk JavaScript, anyway.

So, you could "try" to call addEventListener and if you "catch" an error you could then call attachEvent.

Just my $0,02.

I've recently faced the addEventListener issue myself, so here's my current approach on the matter:

functionaddEventListener(target, type, listener) {
    if (target) {
        if (target.addEventListener) {
            target.addEventListener(type, listener, false);
        }
        elseif (target.attachEvent) {
            target.attachEvent("on" + type, listener);
        }
    }
    else {
        thrownewError("Can't addEventListener: target object is null.");
    }
}

Then you just call the new addEventListener function, which carries away with whatever the browser supports.

Post a Comment for "Addeventlistener Code Snippet Translation And Usage For Cross-browser Detectioin"