Chapter 20. Writing Cross-Browser Event Handlers

In ye olden days, the common approach to cross-browser scripting was similar to the solution at the end of Lesson 19: Create multiple pages for each browser type. The solution worked, but the amount of time involved grew according to how many different browsers you wanted to support. As years moved on, the accepted approach was simply to branch code (using an if statement to determine what method to use) when needed, like this:

// assume el variable is an element object
if (typeof addEventListener === "function") {
    el.addEventListener("click", function() {
        alert("You clicked me!");
    }, false);
} else if (typeof attachEvent !== "undefined") {
    el.attachEvent("onclick", function() {
        alert("You clicked me!");
    });
} else {
    el.onclick = function() {
        alert("You clicked me!");
    };
}

What you see here is a type of browser detection called feature detection — the detection of certain features, like addEventListener(). The idea is to determine whether the browser supports a particular feature and, if so, to use it. If the feature isn't supported, you fall back to a feature you know will work. In the preceding example the code checks for the addEventListener() method (which all standards-compliant browsers support) and uses it if it is found. If the browser does not support addEventListener(), then the code attempts to identify the browser as a version of IE and, if so, uses attachEvent(). If the browser does not support either addEventListener() ...

Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.