WebReference.com - Creating a Cross-Browser (DOM) Expandable Tree (1/5) | WebReference

WebReference.com - Creating a Cross-Browser (DOM) Expandable Tree (1/5)

current pageTo page 2To page 3To page 4To page 5

Creating a Cross-Browser (DOM) Expandable Tree

By Nicholas C. Zakas (nicholas@nczonline.net)


As a user interface designer for Web applications, I find that there is a constant need (read: demand) for certain UI components across the board. The most commonly requested component is an expandable/collapsible tree, often referred to as an explorer tree (referring to its use in Microsoft Windows Explorer).

Previously, it could take a lot of time and effort to create a tree that could work in both Internet Explorer and Netscape Navigator. With recent improvements in Internet Explorer and Netscape, however, it is possible to make an expandable tree without needing any browser detection whatsoever.

This article will focus on building a JavaScript tree. The target browsers for this tree are Internet Explorer 5.0+ and Netscape 6.1+ (Netscape 6.0 had many bugs that could affect the proper display of the tree). This tree will be built with cross-browser code that works on both IE5+ and NS6, so that the code requires no browser detection to work on these two browsers (note that if your users may still be using IE4 or NS4, you will need to do an additional browser detect to see if you can use the code in this article).

The style of tree will be the style of Windows XP because it does not include the complicated lines as in previous versions of Windows... plus, it has some really nice graphics.

Step 1: Define Global Variables

I always begin these projects by determining what global variables and constants will be needed. In this case, we have two images that must always be used: the plus and minus images. Regardless of what else is in the tree, the plus and minus images are always used. These images are loaded into native JavaScript Image objects in order to assure that the images are loaded when the tree begins to draw.

Another global variable will serve as a generic pointer to the instantiated tree object. We will call this objLocalTree. No matter what variable name is used to instantiate a tree object, it can always be referenced through objLocalTree (this is assuming that there is only one instance of the tree per frame).

A global constant that is needed is the indent width for the tree. This is the indent for each level of the tree in pixels. By default, it will be set to 18.

The code for this is as follows:

var DIR_IMAGES = "images/";
var IMG_PLUS = DIR_IMAGES + "btnPlus.gif";
var IMG_MINUS = DIR_IMAGES + "btnMinus.gif";
var imgPlus = new Image();
imgPlus.src = IMG_PLUS;
var imgMinus = new Image();
imgMinus.src = IMG_MINUS;
var objLocalTree = null;
var INDENT_WIDTH = 18;

current pageTo page 2To page 3To page 4To page 5

Created: February 20, 2002
Revised: February 20, 2002

URL: http://webreference.com/programming/javascript/trees/