Categories:
Partners

Using object detection to detect support for a property or method

So, what is object detection? Well. it's using JavaScript to detect whether the surfer's browser supports a particular object or not. Ok, not exactly helpful, but bare with me as I explain this concept.

Most people are familiar with the "if" statement of JavaScript. What most people are not familiar with, though, is that you can actually use an object's property or method inside the parenthesis of an "if" statement. For example:

<script type="text/javascript">
if (document.forms)
//do something
</script>

"What on earth does the above 'if' statement detect?", you may ask. Well, whether the running browser supports the forms object or not. By putting an object's name inside an "if" statement, the statement evaluates to true only if the object is defined (is supported), thus the name "object detection".

Detecting support for a property or method

Now, to elaborate on the idea of object detection, really what you can do is detect both support for a particular JavaScript property or method. Here's an example of each:

<script type="text/javascript">
if (window.screen) //detect support for the Screen property (also an object)
var screenWidth=screen.availWidth

if (document.getElementById) //detect support for document.getElementById() method
var divobj=document.getElementById("test")
</script>

In both cases, if the visitor's browser doesn't support that property or method, it returns null, causing the "if" statement to evaluate to false (and hence the containing code not executed).

What to watch out for

When using object detection, you should always ensure that the parent object containing the property or method you wish to detect is supported first before testing for the property/ method itself. Otherwise, non supporting browsers will return an error, since it doesn't even recognize the object you're referencing, let alone whether that object supports a particular property or method! In cases where the parent object is a universal one such as "window" or "document", as in the above examples, there's no need to perform this check, but lets say your target property is "screen.pixelDepth". This property is only supported in Netscape and Firefox, not IE. Here's the correct way to test for it:

<script type="text/javascript">
if (window.screen && window.screen.pixelDepth)
var screenDepth=screen.pixelDepth
</script>

Notice how I first test for the screen object itself, then the "pixelDepth" property for it. This set up ensures that if the user's browser doesn't even support the screen object, the "if" condition immediately evaluates to false without testing for the second part of the expression, and the containing code is not executed.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.