The JavaScript Tree Component
Creating Cross-Browser Dynamic HTML Trees
By Gary Smith
Send comments and
questions about this article to View Source.
The free-to-the-public JavaScript Tree component enables
you to build customized tree
hierarchies made up of pure cross-browser
Dynamic HTML (DHTML) using object-oriented JavaScript.
By providing the tree hierarchy that's common in most graphical user
interfaces (GUIs), this component can improve both the navigation and the
real estate of your web pages. And it's not only cross-browser, but
also cross-platform (running on Unix, Linux, Mac, and Windows).
I'll show you how to take advantage of the
JavaScript Tree component and use it in your web site or application.
(Note that only browsers from version 4 on
will display the DHTML trees; version 3 browsers will simply ignore them.)
You can download an archive containing all the
tree-related source files that go with this article.
If you're new to JavaScript, this is a great place to learn. Also note the references listed
under Further Resources at the end of this article - in particular,
the Frequently Asked Questions
(FAQ) page for the
Tree component.
GETTING STARTED
To begin, you need to add the following library inclusion code into your web page source:
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
if (document.layers) {
document.writeln('<SCRIPT SRC="tree_n4.js"><\/SCRIPT>');
} else if (document.all) {
document.writeln('<SCRIPT SRC="tree.js"><\/SCRIPT>');
}
//-->
</SCRIPT>
Here a pair of standard HTML <SCRIPT> tags
enclose five lines of JavaScript code for including a JavaScript library in your web page source.
This library contains the code for the JavaScript
Tree component, which consists of several JavaScript functions
that you'll need for creating trees.
It's best to place this library inclusion code in the
<HEAD> section of your page source
(see the sample source).
Note that due to the document object model (DOM) differences between Netscape Navigator 4 and
Microsoft Internet Explorer 4,
I've created two separate library files, one
for each web browser: tree_n4.js and tree.js.
Thus, the library inclusion code contains an if-else construction
to dynamically include the proper library (via JavaScript's document.writeln() method)
for the browser being used.
Once you've inserted this code into your web page, you can begin to create trees.
CREATING A TREE
The JavaScript
Tree component is object-oriented and
provides an application programming interface (API)
that includes a constructor and a collection of member functions, procedures,
and variables for creating "tree objects."
You create a tree object by using the JavaScript
new operator
and the Tree()
constructor, as follows:
var myTree = new Tree();
This expression creates a tree object named
myTree.
Once you've created a tree object,
you can add "tree items" to it with
the addTreeItem()
method, which is built into the
Tree
component. For example:
myTree.addTreeItem("my item");
You can pass any text string
as a label argument to
addTreeItem(); this string will appear
as the label for the text item when the tree is displayed. To continue adding tree items, keep calling
addTreeItem(),
as shown in the sample script in Example 1.
(If you're familiar with the JavaScript
Menu component,
you may have noticed that the syntax of the
Tree API
is very similar to the
Menu API;
using the addTreeItem() method in the
Tree component is analogous to using the
addMenuItem() method in the
Menu component.)
Example 1
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
var myTree = new Tree();
myTree.addTreeItem("my tree item A");
myTree.addTreeItem("my tree item B");
myTree.addTreeItem("my tree item C");
myTree.addTreeItem("my tree item D");
//-->
</SCRIPT>
This script creates a simple tree object composed of four tree items,
each with its own string label:
"my tree item A",
"my tree item B", and so on.
To create a more useful tree GUI,
you'll need to create a hierarchy of tree objects, which the following section illustrates.
CREATING A TREE HIERARCHY
Once you create a tree object,
you can use it as a child for the preceding tree object that you create
(as with the
child
API in the
Menu component),
thus creating a tree hierarchy. The sample script in Example 2
creates a small tree hierarchy. (Later, in the Adding Links section, you'll see
an example of a bigger tree hierarchy.)
Example 2
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
var mySubTree = new Tree();
mySubTree.addTreeItem("subTree item a");
mySubTree.addTreeItem("subTree item b");
mySubTree.addTreeItem("subTree item c");
mySubTree.addTreeItem("subTree item d");
var myTree = new Tree();
myTree.addTreeItem(mySubTree);
myTree.addTreeItem("my tree item A");
myTree.addTreeItem("my tree item B");
myTree.addTreeItem("my tree item C");
myTree.addTreeItem("my tree item D");
//-->
</SCRIPT>
Example 2 creates a small hierarchy of tree objects by passing the
mySubTree
object as the first argument in one of the
addTreeItem() calls for the myTree object.
Thus the mySubTree object becomes the child of the parent (myTree) tree.
To see the hierarchy of tree objects created by Example 2, click the following link,
which will open a window that contains a page displaying that tree hierarchy.
Display Example 2 Tree
If you view the source of that page, you'll notice that there's also a call to a function named
showTree(),
which is a core method of the Tree component.
This function tells the Tree component that your tree hierarchy is ready to be displayed.
You only need to call showTree() once for the
first tree object (the root-level object) of your tree hierarchy.
Once the root tree is displayed,
the Tree component will take care of displaying the rest of the tree objects in your hierarchy,
by displaying a folder icon for each of the tree items that contain child trees.
Clicking one of these icons will open that folder,
displaying all the tree items in its child tree.
Nesting Further Down in the Hierarchy
To create a deeper tree hierarchy, you can continue to nest
tree objects via the
addTreeItem() method.
Example 3 shows how to
create a deeper hierarchy using more tree objects.
Example 3
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
var mySubSubTree = new Tree();
mySubSubTree.addTreeItem("my subTree item A");
mySubSubTree.addTreeItem("my subTree item B");
var mySubTree = new Tree();
mySubTree.addTreeItem(mySubSubTree);
mySubTree.addTreeItem("my subTree item B");
var mySubTree2 = new Tree();
mySubTree2.addTreeItem("my subTree item A");
mySubTree2.addTreeItem("my subTree item B");
var mySubTree3 = new Tree();
mySubTree3.addTreeItem("my subTree item A");
mySubTree3.addTreeItem("my subTree item B");
var myTree = new Tree();
myTree.addTreeItem(mySubTree);
myTree.addTreeItem(mySubTree2);
myTree.addTreeItem(mySubTree3);
myTree.addTreeItem("my last tree item");
//-->
</SCRIPT>
Display Example 3 Tree
Example 3 creates five tree objects:
myTree is the root-level object.
mySubTree, mySubTree2, and mySubTree3
are all first-level tree objects (siblings of the root tree, myTree).
mySubSubTree is a second-level tree object
(a child of mySubTree, which is a child of the root tree).
You can keep nesting tree objects in a tree hierarchy in this way;
there's virtually no limit to the hierarchical depth of
the
Tree component.
Displaying the Tree Hierarchy in a Frame
As in most applications,
you probably want your tree hierarchy displayed to the left of your main content.
Click the following link to open a window
containing a simple HTML frameset composed of two frames, where the left frame
is a page displaying the tree hierarchy created by Example 3.
Display Frameset
To see how this was done, view the source of these frameset pages.
(I assume you're familiar with the basic syntax of HTML framesets.)
ADDING LINKS
Now that you know how to create tree objects and hierarchies,
let's look at how to add links to the individual tree items.
Example 4 creates another, more useful tree object that contains links.
Example 4
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
var myTree = new Tree();
myTree.addTreeItem("DevEdge", "location='http://developer.netscape.com'");
myTree.addTreeItem("Download", "location='http://developer.netscape.com/download/'");
myTree.addTreeItem("View Source", "location='http://developer.netscape.com/viewsource/'");
myTree.addTreeItem("Mozilla", "location='http://www.mozilla.org'");
//-->
</SCRIPT>
This example is similar to the previous sample trees,
but it passes a second argument to
addTreeItem().
I've actually defined addTreeItem() to take two arguments:
a label and an action argument.
The action argument is for setting the JavaScript action or function
that should be executed when the user clicks the tree item.
In Example 4, I set all the tree item actions so that the browser
will change the location of the page to a specified URL.
Notice that like the label argument, the action argument is a text string,
but in this case a string of code.
Wrapping the action code in a string makes it possible
to pass practically any kind of action,
including a call to a JavaScript function or expression,
without having the action performed until the click event takes place.
For example, instead of passing a string of code like
"location='http://developer.netscape.com'" for the item action
(as in Example 4), we could pass
"window.open()" to open a new browser window.
Adding links and other JavaScript actions will make your tree hierarchy more useful.
For instance, a site map - a tree hierarchy based on your web site structure -
can be a very useful, interactive tool for users, to help them find what
they're looking for more quickly.
Click the following link to open a window containing a sample site map
displayed in the left frame, similar to the previous example.
Display Site Map
This particular sample is a site map (tree hierarchy)
based on the DevEdge Online web site structure. See also the
Netscape Site Map
and the Mozilla Site Map,
and try creating the same type of map for your web site or application.
CUSTOMIZING TREES
I've extended the API of the
Tree component in ways that
allow you to customize the look and feel of your trees.
For example, you can change the font, size, color, and icon images of your trees
by changing the default tree properties contained in the Tree component.
Click the following link to open a window containing a
sample tree hierarchy
that resembles an electronic mailbox.
Display Mailbox
This tree sample is not a functional web mailbox,
but it could be with more back-end work.
It uses the same
Tree component as the previous samples,
but with different icon images.
It does this by changing the default icon properties for the newly created tree objects,
as follows:
myMenu.folderIcons = new Array("images/mailfolder.gif",
"images/mailfolder_h.gif",
"images/mailfolder_s.gif",
"images/mailfolder_sh.gif");
myMenu.itemIcons = new Array("images/mailitem.gif",
"images/mailitem_h.gif",
"images/mailitem_s.gif",
"images/mailitem_h.gif");
These lines of code override the myMenu icon properties: folderIcons and
itemIcons.
(You can copy these sample code lines and put in the path to your own images.)
These icon properties are both JavaScript Array types.
Each array contains four elements, in this order:
- the base icon, before any mouse events are encountered
- the icon when the mouse pointer rolls over it (the "highlight" icon)
- the icon when the user clicks it (the "selected" icon)
- the icon when the mouse pointer rolls over the selected icon (the "selected highlight" icon)
You'll therefore need to provide four different icon images for each of the two icon property arrays.
The folderIcons array
refers to the folder icons for the tree object,
while the itemIcons array refers to the tree's single-item (nonfolder) icons.
View the page source of the sample
Mailbox
and
File Manager
trees to see examples of customized icon properties.
There are several other properties that you can
customize in the Tree prototype object.
See the Sample Trees page for
additional samples of customized trees.
Drag and Drop
You also have the option of enabling drag and drop for the items in your tree hierarchy.
This useful feature allows a tree item to be dragged from one folder and dropped it
another within your tree structure (as in any common tree GUI).
For instance, the
File Manager
sample enables drag and drop.
To enable drag and drop for the items in your tree hierarchy,
you need to load an additional JavaScript library into your page source,
as follows:
<SCRIPT LANGUAGE="JavaScript1.2" SRC="features.js">
</SCRIPT>
This library (features.js) contains several JavaScript functions for
enabling drag and drop (as well as other extra features).
Once you include the features.js library,
all your tree items will be draggable by default.
Click the following link to open a window
containing a sample tree hierarchy that includes the features.js library
and thus enables the drag and drop feature.
Display Draggable Tree
If you have drag and drop enabled for your tree hierarchy
but want to disable it for a particular tree,
you'll need to set the disableDrag property to true
for that tree. For example:
myTree.disableDrag = true;
This statement disables drag and drop for the tree items in the
myTree object,
while leaving the rest of the items in the tree hierarchy draggable.
GOING FORWARD
I hope you've enjoyed this article and that it will help you add
better navigation to your web site. I've covered
every detail I could think of to enable you to customize and add trees to your web pages.
Remember to check out the Sample Trees page for a list
of other tree samples.
FURTHER RESOURCES
JavaScript Resources
Dynamic HTML Resources from World Wide Web Consortium (W3C)
View Source wants your feedback!
Write to us and let us know
what you think of this article.
Many thanks to Michelle Wyner and Paul Dreyfus for the opportunity to write this article,
and special thanks to
Caroline Rose for the excellent editing job.
Gary Smith is a Netscape engineer
who occasionally writes free-to-the-public software, and
articles such as
The JavaScript Menu Component
and
Connecting JavaScript to Java With LiveConnect in View Source.
(11.99)
Any sample code included above is provided for your use on an "AS IS" basis, under the Netscape License Agreement - Terms of Use