Sunday, February 25, 2007

Peter-Paul Koch: Object detection

If you want to use an advanced bit of script, you first have to check whether a browser supports the objects you want to use. This page explains how to do it.

De a lenyeg:

If you want to know whether the browser that views your page supports certain objects you want to use in your code, you should never EVER use a browser detect.

Instead, we simply look if the browser supports the object (method, array or property) we want to use. Let’s continue with the mouseover example. This script relies on the document.images array, so first and foremost we’ll have to detect if the browser supports it. This is done by

if (document.images)
{
do something with the images array
}

Another common detect is for window.focus. This is a method (a command by which you tell JavaScript to do something for you). If we want to use the method, we’ll have to check first if the browser supports it.

Note the correct way of doing this: you ask for the method without brackets. This code

if (window.focus)

means: “If the focus method is supported”, while this code

if (window.focus())

means: “If you can put the focus on the window” and assumes that focus is supported. If it isn’t, this line of code creates errors. The brackets () actually execute the focus command, which is not what we want in this case. So we check it without the brackets (see if it exists) and only when the browser passes the check we actually execute the command by adding brackets:

if (window.focus) window.focus()

So the whole point is that if you want to use the array document.images, first check if it is supported. If you want to use the focus method of the window, first check if it is supported.

If you always use object detection, your scripts will never generate any error messages, although they might not work in certain browsers.