Preparing the Style Sheet
The code for the tree control naturally breaks down into three sections: the CSS, the HTML, and the JavaScript. Open your favorite text editor and create the HTML container and the CSS rules with the following code:
The CSS rules are simple. The body rule sets the font and foreground (text) color of the document. The trigger rule simply ensures that any node that has children will use the hand cursor when the mouse moves over it. Two cursor properties are necessary because IE and Netscape use different identifiers.
The branch rule applies to content that needs to toggle on and off, in other words, child nodes. Setting the display property to "none" ensures that the tree will be completely contracted when the page loads. In my script, I'll set the display property to "block" to show a given node and set it back to "none" to hide the node. Note that the CSS visibility property doesn't accomplish the same thing as the browser will set aside the amount of space necessary for the branch to display even if the visibility property is set to "hidden."
Problem: Screen real estate is at a premium on many Web pages. Developers need a way to present a lot of information in a limited space. But users need familiar user interface conventions. How do you get more information in a smaller space without confusing end users?
Solution: Build a familiar tree control using some simple style rules, a few graphics, and some JavaScript.
HTML and JavaScript-based trees are becoming more common every day. Are you using tree controls already? Are you using a commercial version or did you roll your own. What do you think of this article's approach to implementing a tree control? Join the discussions at Web.dhtml.general or Web.dhtml.scripting to get answers, make comments, or help others with their problems.