Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

Language Essentials

  • Print
  • + Share This
This chapter is from the book

Detecting Objects

When you're scripting, you may want to check to see if the browser is smart enough to understand the objects you want to use. There is a way to do this check, which is called object detection.

What you do is pose a conditional for the object you're looking for, like this:

if (document.getElementById) {

If the object exists, the if statement is true, and the script continues on its merry way. But if the browser doesn't understand the object, the test returns false, and the else portion of the conditional executes. Script 3.5 gives you the JavaScript you need, and Figure 3.3 shows you the result in an obsolete browser.

Script 3.5. Object detection is an important tool for scripters.

window.onload = newCard;

function newCard() {
    if (document.getElementById) {
       for (var i=0; i<24; i++) {
          setSquare(i);
       }
    }
    else {
        alert("Sorry, your browser doesn't support this script");
    }
}

function setSquare(thisSquare) {
     var currSquare = "square" + thisSquare;
     var newNum = Math.floor(Math.random() * 75) + 1;

     document.getElementById(currSquare). innerHTML = newNum;
}
Figure 3.3

Figure 3.3 Object detection rejected this ancient browser (Netscape 4 for Mac) and displayed this error message.

To detect an object:

  1. if (document.getElementById) {
    
    This line begins the conditional. If the object inside the parentheses exists, the test returns true, and the rest of this block in the newCard() function runs.
  2. else {
      alert("Sorry, your browser doesn't support this script");
    }
    
    If the test in step 1 returns false, this line pops up an alert, and the script ends.
  • + Share This
  • 🔖 Save To Your Account