DHTML Collapsing Treeview

y now, I’m sure that you have some Web development experience, either with VB DHTML applications, or HTML pages using VBScript. If not, then you will soon, so pay attention. We’ll build a collapsible treeview using DHTML. Along with gaining an understanding of a very useful technique, you will be learning some neat features of DHTML, such as event bubbling and working the DHTML hierarchy.

First, you must make sure that your browser supports DHTML. Then, we will build a treeview that can have an endless amount of sub-nodes and expands and collapses when a parent node is clicked. The HTML for the tree is made up of tags with two classes. The parent class represents a parent node, and the childrenContainer class represents a container for all the children of a parent node. Any element within the document can be a parent class and have its own collection of children in a childrenContainer class. The HTML is listed at the end of this page.

Now let’s talk about the code. DHTML is arranged in a hierarchy with the Window object (BaseWindow in VB) at the top. After that comes the Document object, then the rest of the elements of the page are children of the Document object and are hierarchically arranged as they are nested within each other. When an event is raised for an element it is also raised for all its parent elements, which is known as event bubbling. To access the child elements of an element you can either use the Children property, which returns all the immediate children, or the All property, which returns all children regardless of how many levels deep they are.

The code for the treeview works as follows. In the Document’s on_click event we check to see which class of element raised the event. If it is a parent class, then we get its child element that is a childrenContainer class and toggle its visibility. Here’s the code for VBScript, to run it in a VB DHTML application, just change the Window object on the second line to BaseWindow.

Sub document_onclickset obj=window.event.srcElementselect case obj.classNamecase "parent"	set objChildren=getChildbyClass(obj.children)	if 	objChildren.style.display="none" then		objChildren.style.display="inline"	else		objChildren.style.display="none"	end ifend select  End SubFunction getChildbyClass(children)for i=0 to children.length-1	if children(i).classname="childContainer" then		set getChildbyClass =children(i)		exit for	end ifnext End function 

For the final touch we’ll add a little style so that child elements are indented and that the cursor changes to a hand when it moves over a parent node. The HTML for the style is listed together with HTML below. (Click here to see an example)

Parent 1
Child 1
Child 2
Child 3
Parent 2
Child 1
Grandchild 1
Great Grandchild 1
Great Grandchild 2
Great Grandchild 3
Grandchild 2
Grandchild 3
Child 2
Child 3
Parent 3
Child 1
Child 2
Child 3
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: