Click here to Skip to main content
Click here to Skip to main content

Easy DHTML treeview

, 21 Feb 2002
Rate this:
Please Sign up or sign in to vote.
A relatively easy implementation of a treeview using DHTML (Client Side Javascript in conjunction with DOM). This implementation is straightforward and doesn't require the filling of java-arrays.
<!-- Download Links --> <!-- Article image -->

Sample Image - DHTML_Treeview.jpg

<!-- Add the rest of your HTML here -->

Introduction

Have you ever tried to insert an easy-to-use treeview into your homepage or even use a treeview in your web-application? If you have, you will probably know that most ready-made treeviews out there are built in a quite complex manner, making heavy use of client side javascript and difficult-to-handle structures like multi-dimensional arrays and such. There is, however, a more elegant way of implementing a treeview using only one small client-side javascript and making use of DOM (Document Object Model) and basic HTML-tags such as DIV.

Easy DHTML Treeview

The 'Easy DHTML Treeview' builds a treeview on top of the Document Object Model, which already is hierarchical by definition. The whole idea of the 'Easy DHTML Treeview' is using simple HTML tags such as DIV and A to create the real tree and then using one simple javascript function (triggered by clicking on a branch) to collapse and unfold all of the children (branches and leaves) by hiding or showing the DIV-item (if a DIV item is hidden, all the children of the DIV item are hidden as well).

Overview of design

So, when you click on the yellow 'branch name', the javascript function Toggle will be called with a pointer to the branch name itsself. The Toggle-function will then ask the document (using DOM) what the next item is (which in this case is the yellow DIV-section) and hide it. If the yellow DIV-section is hidden all items inside the yellow square (which is almost everything in the picture) will be hidden as well.

Serialising the treeview

The good thing about this simple implementation is that it is very easy to construct a treeview from data that can be stored in a database. Whereas other treeview functions and components force you to fill a javascript array (which is only 2 levels deep anyway and therefore not a real n-level tree), 'Easy DHTML Treeview' allows you to simply print the data as if it were a table. The whole functionality of collapsing and unfolding the branches in the tree is then added almost automatically by the single function that does it all!

The included demo-project shows you that it is really quite easy to create very dynamic, n-level truly recursive trees using 'Easy DHTML Treeview'. For storing the data in the tree, this data model is used:

E-R Diagram

Like a treeview, the data model itself is recursive, because topic and topic_1 are the very same table. This means topic has a relation to topic, with the subtopic table in between to implement an n-n relationship.

Tips & Tricks

I got a lot of questions about the treeview so I'd just answer some of them here for your convenience:

How can I change the initial state of the treeview from collapsed to expanded? The answer is quite simple. If you're using the static version (from the live demo-site, simply omit the style attribute from the DIV-tags. So what was < DIV style='display:none' > simply becomes < DIV >. And of course if you're into details, you should change the images in front of the items from plus.gif to minus.gif. If you're using the scripts that generate a tree from a database, you should hack it the other way around, because that sample is initially expanded. It's quite straightforward, but when I find the time I could post 2 versions of the samples, one collapsed and the other one expanded.

How can I liven up the treeview to make it look better? Well, I've been working on a pure-HTML extension of the treeview with a colleague of mine, which draws lines in the treeview, like MFC treeviews do. I will post this version shortly.

Cross-browser treeview?

I developed this treeview for Internet Explorer 5, which is not such a good idea if you want to develop a cross-browser treeview because Microsoft has the tendency to build all kind of fancy non-standard goodies into it's browser. Luckily some people on the CodeProject have tested it on other browsers and it only seemed to work on IE5 (not even IE4!). I'm now in the process of evaluating what I can do to improve this. Today (June 13th 2001) I checked all my script-entries against the actual standards and found out that all of it should work on browsers supporting CSS Level 1, HTML 4.0 and DOM Level 2. I made some modifications today as well and I'm curious on which browsers the script works correctly.

The treeview has been tested on the following browsers:

Microsoft Internet Explorer 4 (SP 2)Doesn't Work!
Microsoft Internet Explorer 5.0 (for Macintosh)Work partially (different look)
Microsoft Internet Explorer 5.00.3103.1000Works!
Microsoft Internet Explorer 5.50.4522.1800C0Works!
Microsoft Internet Explorer 6.00.2462.0000Works!
Netscape 4.77Doesn't work!
Netscape 6Works!
Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; 0.8.1) Gecko/20010323Works!
Opera 5.0 (Build 528 on Windows 2000)Doesn't work!
Opera 6Doesn't work!

(Thanks to Jorge Sabater Redondo, Alexandra Berg, Neal Costello, Zinggl Alois, Jens Kreiensiek, Arnt Witteveen, Jamie Nordmeyer, Bryan Pietrzak and Bruce for the testing!)

If you have another browser than listed above, please test the script at THIS live-demo site and mail me to tell me if it did or didn't work on your browser... Together we can build a better treeview, I know it! Wink | ;-)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

D.D. de Kerf
Web Developer
Netherlands Netherlands
I completed college Higher Informatics (HIO Breda, The Netherlands) in august 2000. I have been software engineer/documentalist/project manager with Bodégro Technical Automation since 1998 (started as part-time, full-time since august 2000).
 
Lots of experience with Delphi, Visual C++, PL/SQL, ASP and PHP. Started a succesfull knowledge-sharing initiative in late 1999 called 'Cohort Forum', which resulted in a web-site a lot like the codeproject.

Comments and Discussions

 
QuestionHREF PinmemberMichael Janulaitis18-Jan-12 11:49 
QuestionWorks In Chrome PinmemberDaaron11-Jul-11 7:02 
GeneralIE8 PinmemberZe2103826-May-10 4:03 
GeneralThank you PinmemberOmarGamil31-Oct-09 22:57 
GeneralFROM ASP TO PHP AND MYSQL Pinmemberpogramadox9-Oct-09 9:05 
Thanks, great code, here is in php. Just copy and paste into the two code files. The database named test was exported as sql from phpMyadmin. It's dump is down.
 
FIRST demo.php:
 
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft FrontPage 4.0">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
<TITLE>Easy DHTML TreeView dynamic sample</TITLE>
</HEAD>
<BODY>
 
<?php include("DHTML_TreeView.inc"); ?>
<HR>
<?php

// Init the treeview
InitTreeView();
 
// Get the topics from the database and draw the treeview
TopicsInTree();
?>
 
<BR><BR><HR>
<SCRIPT LANGUAGE="JavaScript">
 
//execute once page has loadded
var aTags = document.getElementsByTagName('A');
 
for(var n = 0; n < aTags.length; n++)
{
if(aTags[n].onclick.toString().indexOf('Toggle(this)') > 0)
{
Toggle(aTags[n]);
}
}
 
</SCRIPT>
 
</BODY>
</HTML>
 
AND LAST DHTML_TreeView.inc
 
<?php
function InitTreeView(){
?>
 
<SCRIPT LANGUAGE="JavaScript">
 
// ---------------------------------------------
// --- Name: Easy DHTML Treeview --
// --- Author: D.D. de Kerf --
// --- Version: 0.1 Date: 6-6-2001 --
// ---------------------------------------------
function Toggle(node)
{
// Unfold the branch if it isn't visible
if (node.nextSibling.style.display == 'none')
{
// Change the image (if there is an image)
if (node.childNodes.length > 0)
{
if (node.childNodes.item(0).nodeName == "IMG")
{
node.childNodes.item(0).src = "minus.gif";
}
}
 
node.nextSibling.style.display = 'block';
}
// Collapse the branch if it IS visible
else
{
// Change the image (if there is an image)
if (node.childNodes.length > 0)
{
if (node.childNodes.item(0).nodeName == "IMG")
{
node.childNodes.item(0).src = "plus.gif";
}
}
 
node.nextSibling.style.display = 'none';
}
 
}
</SCRIPT>
<?php
 
} ////////////////
 

// Helper function for TopicsInTree. This function will be called recursively to load the whole tree from
// the database
function SubTopicsInTree($DBconnection, $topicID, $topic, $depth){
 
// Query the database for all the direct subtopics of topic topicID
$query = "SELECT topicID, name FROM topic WHERE topicID IN (SELECT subtopicID FROM subtopic WHERE topicID = ".$topicID.") ORDER BY name ASC";
$rsSubtopics = mysql_query($query, $DBconnection);

$la="<FONT FACE='arial' SIZE='".(6-$depth)."'>";
$lc= "</FONT>";
echo "<TABLE BORDER=0><TR>";

// This value (now 10) represents the hoziontal spacing between the branches
//if ($depth > 1)
echo "<TD WIDTH=20></TD>";

 
// We have another branch. Solve the branch recursively
if(mysql_num_rows($rsSubtopics) > 0){

echo "<TD><A onClick='Toggle(this)'><IMG SRC='minus.gif'> ".$la.$topic.$lc."</A><DIV>";
while ($row = mysql_fetch_array($rsSubtopics)) {

$subtopicID = $row[0];
$subtopic = $row[1];
SubTopicsInTree($DBconnection, $subtopicID, $subtopic, ($depth + 1));

}
 
// We have a leaf. Simply print the leaf
}else{
echo "<TD><IMG SRC='leaf.gif'> ".$la.$topic.$lc."<DIV>";
}

echo "</DIV></TD></TR></TABLE>";

mysql_free_result($rsSubtopics);
}
 

// The function that loads the treeview from the database and draws it in HTML
// Connect to the database
function TopicsInTree()
{
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "test";
 
$connection = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect to DB");
mysql_select_db($db_name, $connection);

 

// Query the database for topics that are no subtopic (so we'll get only the main topics)
$query = "SELECT topicID, name FROM topic WHERE topicID NOT IN (SELECT subtopicID FROM subtopic) ORDER BY name ASC";
$result = mysql_query($query, $connection);
echo "<TABLE BORDER=0>";
 

while ($row = mysql_fetch_array($result)) {
echo "<TR><TD>";
$onderwerpID = $row[0];
$onderwerp = $row[1];
 
// Every main topic is a branch of it's own, so they have to be solved
// recursively
SubTopicsInTree($connection, $onderwerpID, $onderwerp, 1);
echo "</TR></TD>";
}

echo "</TABLE>";
 
mysql_free_result($result);
mysql_close($connection);
 
}
 
?>
 
database test dump
 
-- phpMyAdmin SQL Dump
-- version 3.2.1
-- http://www.phpmyadmin.net
--
-- Servidor: localhost
-- Tiempo de generación: 27-01-1980 a las 01:56:53
-- Versión del servidor: 5.1.37
-- Versión de PHP: 5.3.0
 
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
 
--
-- Base de datos: `test`
--
CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_spanish_ci;
USE `test`;
 
-- --------------------------------------------------------
 
--
-- Estructura de tabla para la tabla `subtopic`
--
 
CREATE TABLE IF NOT EXISTS `subtopic` (
`topicID` int(11) NOT NULL,
`subtopicID` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
 
--
-- Volcar la base de datos para la tabla `subtopic`
--
 
INSERT INTO `subtopic` (`topicID`, `subtopicID`) VALUES
(1, 4),
(1, 5),
(1, 6),
(3, 16),
(3, 17),
(3, 18),
(3, 19),
(4, 7),
(4, 8),
(5, 9),
(6, 10),
(6, 11),
(6, 12),
(11, 13),
(11, 14),
(11, 15);
 
-- --------------------------------------------------------
 
--
-- Estructura de tabla para la tabla `topic`
--
 
CREATE TABLE IF NOT EXISTS `topic` (
`topicID` int(11) NOT NULL AUTO_INCREMENT,
`name` text COLLATE utf8_spanish_ci NOT NULL,
`description` longtext COLLATE utf8_spanish_ci NOT NULL,
PRIMARY KEY (`topicID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=20 ;
 
--
-- Volcar la base de datos para la tabla `topic`
--
 
INSERT INTO `topic` (`topicID`, `name`, `description`) VALUES
(1, 'Animals', ''),
(2, 'Humans', ''),
(3, 'Plants', ''),
(4, 'Cats', ''),
(5, 'Dogs', ''),
(6, 'Fish', ''),
(7, 'Siamese cat', ''),
(8, 'Street cat', ''),
(9, 'Dalmatian', ''),
(10, 'Goldfish', ''),
(11, 'Killer fish', ''),
(12, 'Salmon', ''),
(13, 'Shark', ''),
(14, 'Piranha', ''),
(15, 'Killer penguin', ''),
(16, 'Apple', ''),
(17, 'Pear', ''),
(18, 'Apricot', ''),
(19, 'Banana', '');
Questionadd href? Pinmemberneil.guo4-Nov-07 1:25 
GeneralPerformance Pinmemberjiggyman21-May-07 15:29 
GeneralRe: Performance PinmemberEntropy23-May-07 3:19 
GeneralOne node expanded at time PinmemberLina_7919-Apr-07 4:38 
NewsNew Version PinmemberAndrewVos9-Nov-06 22:18 
GeneralRe: New Version PinmemberLTSpeed12-Nov-06 13:56 
General!!!!How to make code work with FireFox!!!! PinmemberAndrewVos6-Nov-06 1:50 
GeneralUsing event object with tree Pinmemberatomicfroman14-Jun-06 10:08 
GeneralThe way of simplicity is often the best way... Pinmemberachainard16-Apr-06 20:47 
GeneralGreat work Pinmemberprettymeshedup11-Apr-06 6:02 
QuestionTree Performance? Pinmemberkarba3010-Jan-06 18:51 
AnswerRe: Tree Performance? Pinmemberrajdeeep14-Feb-11 22:50 
GeneralRetain the tree navigation path PinsussAnonymous9-Sep-05 9:39 
GeneralRe: Retain the tree navigation path PinmemberCodeAddiction22-Dec-05 9:17 
GeneralTHX so much ! PinmemberKahL18-May-05 6:56 
GeneralMy first thought - this code is is great and is so horribly bloated PinmemberZachJ16-May-05 16:02 
GeneralThe HTML PinmemberRamon Tristani29-Apr-05 21:15 
GeneralA helpful article! PinsussHTML&JavacriptLearner23-Mar-05 17:06 
GeneralRe: A helpful article! PinsussHTML&JavascriptLearner23-Mar-05 18:09 
GeneralHTML treeview Pinmemberrachnadevraj@yahoo.co.in24-Jan-05 18:36 
GeneralMozilla 1.6, Netscape 7.1 support Pinmemberevaki22-Jan-05 6:57 
GeneralExpand/Collapse All Pinmemberdsacker19-Nov-04 6:26 
GeneralRe: Expand/Collapse All Pinmemberdsacker19-Nov-04 6:48 
GeneralRe: Expand/Collapse All Pinmembergewe21-Jun-05 2:01 
GeneralRe: Expand/Collapse All Pinmemberdsacker21-Jun-05 3:24 
GeneralRe: Expand/Collapse All PinsussAnonymous5-Jan-05 3:34 
GeneralRe: Expand/Collapse All Pinmemberhenrikmunthebrun7-Jun-05 21:10 
GeneralRe: Expand/Collapse All Pinmembergewe21-Jun-05 1:53 
GeneralRe: Expand/Collapse All Pinmemberkarba3010-Jan-06 20:21 
GeneralRe: Expand/Collapse All PinmemberMike Tours24-May-07 6:13 
GeneralAdding a click on description Pinmembersanrek23-Jun-04 2:54 
GeneralRe: Adding a click on description Pinmemberrajeevking21-Feb-05 23:45 
GeneralRe: Adding a click on description Pinmembergcsnb28-Mar-06 5:48 
GeneralCross Browser Pinmemberclick.ok6-May-04 5:14 
GeneralDeep links in treeview Pinmemberthilol3-May-04 5:54 
GeneralBrowser Compatibility PinsussStephen Robin22-Apr-04 9:21 
GeneralSimple treeview not working Pinsussrjv_rnjn23-Mar-04 4:39 
GeneralGetting parentElement using dom Pinmemberdevikiran15-Mar-04 19:59 
GeneralRe: Getting parentElement using dom PinmemberD.D. de Kerf15-Mar-04 20:40 
GeneralRe: Getting parentElement using dom PinsussAnonymous23-Jan-05 14:33 
GeneralBrilliant - just a couple of changes PinmemberGeorge Nicoll14-Dec-03 7:07 
GeneralCheeky! PinmemberLeeDaviesVBSource8-Oct-03 2:52 
GeneralRe: Cheeky! PinsussAnonymous21-Jun-05 7:33 
GeneralRe: Cheeky! PinmemberSpiff Dog21-Jun-05 7:35 
Generalgenius! Pinmemberacatalept20-Sep-03 0:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 22 Feb 2002
Article Copyright 2001 by D.D. de Kerf
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid