Cross-Browser Scripting: Introduction - Doc JavaScript | 2 | WebReference

Cross-Browser Scripting: Introduction - Doc JavaScript | 2

Cross-Browser Scripting

Netscape Navigator 4.0x and Internet Explorer 4.0x have much in common, but they also introduce many basic differences. For example, let's discuss a simple element named test, with an absolute position:

<DIV ID="test" STYLE="position: abolute; left: 100; top: 200;">

Since we're only interested in various ways of cross-browser scripting, we'll use a very simple script -- a function that moves this element a given number of pixels in each direction. If you've read the columns at Doc JavaScript, you probably noticed the use of the trinary ?: operator to create cross browser references:

function moveIt(id, x, y) {
  var whichEl = (NS4) ? document[id] : document.all[id].style;
  whichEl.left += x; += y;

As you can see, the function first assigns a reference of the desired object to a local variable named whichEl. The expression document[id] references the element in Navigator 4.0x, while document.all[id], or eval(id), is how we reference it in Internet Explorer 4.0x. However, we need to access the element's left and top properties in order to move it. In Navigator 4.0x, the element itself is the parent of these properties, but in Internet Explorer 4.0x they are actually properties of the element's style property.

By assigning a browser-dependant reference to the whichEl variable, we create a cross-browser object. In other words, we can refer to its properties in both browsers with the use of a single statement:

whichEl.left += x; += y;

If you haven't followed our previous columns, you may not know how we created the NS4 variable. Here's the code for our two standard browser-detection variables:

var NS4 = (document.layers) ? 1 : 0;
var IE4 = (document.all) ? 1 : 0;

NS4 is true if the browser supports the document.layers object. In other words, it is true for Navigator 4.0x. The second variable, IE4, is true if the browser supports the document.all object. That is, it is true for Internet Explorer 4.0x. Note that 1 and 0 are equivalent to true and false. We use them because they are shorter.

Before we continue, let's take a look at another version of our moveIt() function:

function moveIt(id, x, y) {
  if (NS4) {
    document[id].left += x;
    document[id].top += y;
  } else {
    document.all[id].style.left += x;
    document.all[id] += y;

This function actually splits the work between two sets of statements. The first part of the function moves the element if the browser is Navigator 4.0x, while the second one handles the situation for Internet Explorer 4.0x.

Now that we've covered the well-known basics, it's time to reveal several other techniques. Just keep reading.

Created: June 4, 1997
Revised: June 4, 1997