Web DevCenter    
 Published on Web DevCenter (http://www.oreillynet.com/javascript/)
 See this if you're having trouble printing code examples


Designing with Javascript.

Cross-Browser Style Objects

by Bill Pena, coauthor of Designing with JavaScript, 2nd Edition
01/25/2002

In Chapter 6 ("Too Many Browsers? Not Really") of Designing with JavaScript, 2nd Edition, we explore various techniques for dealing with browser incompatibilities by using browser detection. We can serve different CSS stylesheets to each browser, contain incompatible DHTML in a single frame, or just check if an object is supported.

In this article, adapted from Chapter 11 ("Advanced Applications") of the book, I extend the capabilities of older browsers instead, by recreating crucial W3C DOM features like the style object and the document.getElementById() method, and making them available to 4.0 browsers with proprietary DOMs.

Yes, it seems like you'd need a magical incantation to make all dynamic styles compatible across all browsers, but it is possible. Like all magic, this piece of JavaScript trickery relies on misdirection. By reconstructing DOM features out of each browser's proprietary DHTML extensions, and tying them to common names, this example creates another naming convention different from either the 4.0 browsers' or the W3C's, which you can then use to write browser-independent code.

This example applies the excellent work done by Bob Clary for Netscape, called xbStyle. You can find the latest version of xbStyle, as well as more information on cross-browser scripting, at DevEdge.

Application Programming Interfaces

xbStyle falls into a curious category of scripts called APIs (Application Programming Interface). An API doesn't give a piece of software many new capabilities, as do most scripts, but rather creates an interface through which you can make better use of the software in your own scripts. You could say that the DOM is an API for scripting HTML.

For example, the DOM doesn't invent new HTML elements, but it does let you manipulate those elements that already exist in ways JavaScript can't. xbStyle is an API for Internet Explorer 4, Netscape 4, and W3C style manipulation, giving you access to dynamic CSS styles across all three browsers through one convenient interface. This means that, rather than branching your code to work around incompatibilities, or creating three versions of your scripts altogether, you can write one script using xbStyle that will work the same across all browsers.

Related Reading

Designing with JavaScript, 2nd EditionDesigning with JavaScript, 2nd Edition
By Nick Heinle & Bill Peña
Table of Contents
Index
Sample Chapter
Full Description

In this example, we'll be taking the sliding menus script from Chapter 10 ("Interactive DHTML Techniques") of Designing with JavaScript, and rewriting it to use xbStyle. The original script uses the W3C DOM to slide a layer across the screen, then snaps it back into place when finished. This version follows the same logic as the original, but changes the names to fit xbStyle's conventions.

In order to use xbStyle, you must first link the xbstyle.js file to your document:

<script language="javascript" src="xbstyle.js"></script>

xbStyle also makes use of the Ultimate Browser Sniffer, another JavaScript library from Bob Clary. You'll have to link that file to your document as well:

<script language="javascript" src="ua.js"></script>

Once you've linked your document to the Ultimate Browser Sniffer, you can start writing your script using the API.

Using XBStyle

First, here is the original sliding menu script, outside of its HTML context:

if (parseInt(layer.style.left) <= 0) {
    n = parseInt(layer.style.left);
    layer.style.left = (n + 5) + "px";
    }
else {
    clearTimeout(timeout); 
    }
}

function hideLayer() { 
    var layer = document.getElementById("Layer1");
    layer.style.left = "-75" + "px";
}

This script uses common features of the DOM, including document.getElementById() and the style object. Unfortunately, the way elements are found and how their style properties are accessed vary in the 4.0 browsers. For example, finding an element by its ID, a fundamental DOM function, can be tricky to implement correctly in both Netscape 4 and IE4.

In IE4, elements are accessed through a method similar to document.getElementById(), document.all[]; xbStyle merely takes the ID passed to getElementById(), and redirects it to document.all[] instead, which then returns the appropriate element. In Netscape 4, a <div> with an ID can be accessed only through the document.layers[] array, which is a numbered list of all layers on the page; to compensate, xbStyle checks every element in that list against the ID you're looking for, stops when it finds a match, and returns the correct element.

To your script, it doesn't matter whether xbStyle had to pass the ID to a Netscape or an IE-specific function; it sees only the element the function returned. In other words, all you have to worry about is input and output; if you input the ID, you'll get back the element. This is the essence of an API, to hide the hard stuff and let you get real work done.

Below is the source of xbStyle's getElementById() method; take a look behind the curtain and see how the magic works:

if (navigator.family == 'ie4' && navigator.version < 5) {
  document.getElementById = new Function("id", "return document.all[id];");
  }
  else if (navigator.family == 'nn4') {
    document.getElementById = nav4GetLayerById;
  }

function nav4GetLayerById(id) {
  return nav4FindLayer(this, id);
  }

function nav4FindLayer(doc, id) {
var i;
var subdoc;
var obj;
for (i = 0; i < doc.layers.length; ++i) {
  if (doc.layers[i].id && id == doc.layers[i].id)
  return doc.layers[i];
  subdoc = doc.layers[i].document;
  obj = nav4FindLayer(subdoc, id);
  if (obj != null) {
    return obj;
    }
return null;
}

Screen shot.
Screenshot of the "sliding menu" in action

Cross-Browser Sliding Menus

The two functions in our cross-browser sliding menu, showLayer() and hideLayer(), mimic the behavior of our original script, while changing only what is necessary to achieve compatibility. First and foremost, the primary function of xbStyle is to create a cross-browser style object. However, rather than being an object built into all other elements, as it is in the W3C DOM, you must create a new instance of xbStyle for every element whose styles you need to manipulate. You do this by using the xbStyle constructor function, which takes one parameter, an element ID.

var styleObject = new xbStyle("id");

Once you've created a style object, you can use one of xbStyle's built-in methods, which expand on the W3C and 4.0 DOMs, to manipulate style properties. In this example, we'll be using the following methods from xbStyle:

  1. moveBy(x, y): Moves an element a specified number of pixels along the X (horizontal) and Y (vertical) axes, relative to its current position. This method is equivalent to adding to or subtracting from both the "top" and "left" style properties at once.
  2. moveTo(x, y): Moves an element to a fixed point on the page, defined by its X and Y coordinates. This method is equivalent to setting the "top" and "left" style properties at once.
  3. getLeft(): Returns the value of the style object's "left" property as a number. Note that this is different from what the W3C DOM would return because the number includes the unit "px," for "pixels," at the end of it's value. This means the value is a text string, not a plain number. This is important to remember, because while you can compare two numbers as greater than or less than, as in the example below, you can't do the same with text.
  4. setLeft(n): Takes one parameter, a number, and sets the "left" property of the style object.
  5. document.getElementById(id): Yes, it's also part of the DOM, but xbStyle creates a method of the same name for 4.0 browsers that don't support the W3C DOM, with the same general functionality. If the browser does support the DOM, xbStyle does nothing, and the method works just as expected.

The documentation at DevEdge contains a full listing of all xbStyle objects, methods, and properties.

So, let's take a look at the new and improved sliding menu script, now using the methods above (the letters on the left are for reference only):

function showLayer() {
A    var layer = document.getElementById("Layer1"); 
B    var styleObj = new xbStyle(layer); 
C    var left = styleObj.getLeft(); 
     var timeout = setTimeout("showLayer()", 1);
D    if (left <= 0) { 
E      styleObj.moveBy(5, 0); 
     }
     else {
       styleObj.moveTo(0, 50); 
F      clearTimeout(timeout);
     }
   }

   function hideLayer() {
     var layer = document.getElementById("Layer1");
     var styleObj = new xbStyle(layer);
G    styleObj.setLeft("-75"); 
   }

Try adapting some of your scripts to use XBStyle as well, and you'll save yourself a lot of coding and debugging time while reaching a larger Web audience.

Bill Pena is a freelance Web/information designer and writer. He was also the designer for Safari: Tech Books Online, O'Reilly's online books service.


O'Reilly & Associates recently released (November 2001) Designing with JavaScript, 2nd Edition.

Return to the JavaScript and CSS DevCenter.

Copyright © 2009 O'Reilly Media, Inc.