O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Detecting Object Support

NN 2, IE 3

Problem

You want scripts to run on all browsers that support the objects that your scripts address, and to degrade gracefully in other browsers.

Solution

Surround the script statements that reference potentially incompatible objects with if statements that test for the existence of the objects. The objects you test for can be core JavaScript language objects, as well as DOM objects. Facilitating this kind of condition testing is the fact that a reference to a nonexistent object inside an if condition evaluates to the equivalent of false. A very common usage of object detection from earlier scriptable browsers is in scripts that work with img elements as objects for rollover image swaps (covered in depth in Chapter 12). Support for the img element object was very uneven until the Version 4 browsers. Creating browser version filters for all the possibilities would have been tedious at best. Instead, all script statements that referenced img element objects were wrapped inside an if construction that looks for the presence of the document.images array:

function rollover(imgName, imgSrc) {
    if (document.images) {
        document.images[imgName].src = imgSrc;
    }
}

This function is invoked by an onmouseover event handler associated with a link surrounding an image:

<a href="product.html" onmouseover="rollover('products', 'images/products_on.gif'); return false" onmouseout="rollover('products', 'images/products_off.gif'); return false"> <img src="images/products_off.gif" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required