Treeview Demo Download Install Visual Build FAQ Contact

Treeview JavaScript Applet

Cross-browser DHTML tree


Tree demos
Check the different layouts with these JavaScript demos.

Instructions
Read the installation and configuration instructions.

Apps Using TreeView
 
Web File Browser, PHP and ASP code to automatically generate trees for files.
 
Favorites Manager, ASP code for managing links and bookmarks.
 

Treeview v4.3 - The JavaScript tree menu

Quick install | Quick Config | Page structure | Advanced Config | Server-side options

Quick installation instructions

  1. Download the zip and extract the files to your local machine.

  2. Open index.html in your browser and try the demos to verify that they work in your machine as they do on this site.

  3. For each demo there is only one file that needs to be edited when you want to make changes to the folders or to the links shown by the tree. They are, respectively: demoFramesetNodes.js, demoFramelessNodes.js, and demoLargeNodes.js. Other sections further down in this page provide instructions on how to configure your own tree.

  4. The last step of the installation will be to copy or upload all the files to the actual server that hosts your web site.
This JavaScript + DHTML script will run on both IE and Netscape. Cookies are NOT required by the script, and are only used with the frameless layout.

Quick configuration of your links

The contents of the configuration file (demoFramesetNodes.js, for example) can be generated automatically for you. Take these steps:
  1. Open the Treeview Visual Builder.
  2. Add/edit/delete links and folders dynamically through the graphical user interface.
  3. Press the export button and select "Generate JavaScript".
  4. Open the demoFramesetNodes.js (extracted from the ZIP downloaded from this site) in an editor and erase all contents.
  5. Copy the contents of the pop-up window into the demoFramesetNodes.js file.
  6. Reloading demoFrameset.html should now show all the folders and links you defined in the interactive tool.

A typical tree-holding page

A tree can be placed on the frame of a frameset or on a regular frameless page. The HTML of a tree-holding frame is entirely dedicated to the construction and display of the tree. The frameless tree has additional HTML, unrelated to the tree itself and also sets some configuration variables differently.

However, both types of page share the same structure in terms of sequence and position (HEAD, BODY) of the HTML and JavaScript tree-related statements. That common structure is described in this section.

The structure of the page

Several demos were created that, by providing examples, should make it easy to build pages with trees in them. These demos can all be found in this site's free-download ZIP.

Open in an editor one of the demo HTML files that contains a tree (demoFramesetLeftFrame.html, demoFrameless.html, etc.) As you read this section, try to identify and locate the various tree-related statements in that file.

At the top of the file, in the HEAD block, is the STYLE tag. You can use styles to change the appearance of the tree and of the rest of your page. More details about the STYLE block are given in the next section.

Before the end of the HEAD block, three SCRIPT blocks are required: one to load the browser detection code (ua.js), the other to load the Treeview engine code (ftiens4.js), and the third to load your tree configuration file (demo*Nodes.js, for example.)

Note: in trees driven by server-side code, the tree-configuration statements are actually part of the HTML page not loaded from a separate configuration file.

Other statements unrelated to the tree may also be in the HEAD block, such as JavaScript functions and so on.

Finally, the BODY part of the page contains the statement that actually renders the icons and the hyperlinks of the tree: initializeDocument. For frameless pages with other elements besides the tree, the relative position of the initializeDocument inside BODY depends on the specific layout of your page.

Defining styles for the tree and for the rest of the page

For a frame that contains only a tree, you can control the font, color, etc. of its text using the generic A and TD CSS selectors. However, if you are using a frameless layout and have other elements in the page (namely other A elements) you will probably want a way to specify styles just for the tree.

You can see an example of how this can be done in the files of the frameless demos. The STYLE block is divided in two parts: the tree styles and the other styles.

The way that we are telling the browser which A tags are tree links is by adding a special SPAN block. Look in the body code of these pages and you will see that a SPAN block with a class specifically named TreeviewSpanArea is put around the initializeDocument statement.

That, together with the contextual selectors rules of CSS, does the trick.

Advanced configuration of your links (optional)

The sections Installation and Quick Configuration are the only mandatory steps to get you up and running. If, however, you would rather setup the tree manually and explore all the possible layout and customization options, then you will have to learn more about the contents of the Treeview configuration files (demo*Nodes.js in the ZIP).

Options for layout, look-and-feel, and more

At the top of the configuration file, before the definition of the nodes, is an area to specify layout options and other settings. This is done by assigning values to "environment variables". Leaving this section of the configuration file completely empty will create a tree that uses the default settings. Only variables that will be set a non-default value should be added to the configuration file.

The configuration files inside the free-download ZIP provide examples of some combinations of settings.

The variables, their purpose, and the possible values are listed in the table below.

Treeview configuration variables
Variable nameDescriptionPossible valuesDefault value
BUILDALLFast performance with large or very large trees is obtained by deferring the construction of nodes until the user actually expands the folder that contains them.

By default the BUILDALL variable has the value 0. Setting this variable to 1 will make the script build all the items when the page is loaded, even those that will not be visible because they are inside closed folders.

Currently, there is only one scenario where the tree-configuration file sets this variable. The only case where the construction of nodes cannot be deferred is the Checkbox Tree layout (see demos.) In that case, each node contains a FORM element, and, thus, needs to be built when the page is first loaded.

0 -> defer the construction of hidden items
1 -> write HTML for all items on page load
0
GLOBALTARGETSpecifies the window target of the links in the tree, if that tree was created with the .addChildren API.'R' opens in the right frame (a frame named basefrm),
'B' opens in a new window,
'T' opens in the current browser window, replacing the frameset if one exists,
'S' opens in the current frame, replacing the tree.
'R'
HIGHLIGHTHighlight the text of a folder or "document" node when the node is selected. Typically this option would reverse the foreground and background colors of the clicked node, but any colors may be used. To be able to reload the tree and keep the highlight of the selected node, use the PRESERVESTATE variable.

Only nodes that actually load pages will be highlighted on selection. It is also possible to configure a node that opens pages to not be highlighted. The maySelect member exists both for documents and folders:
  d = insDoc(....
  d.maySelect = false

0 -> do not highlight node
1 -> apply highlight
0
HIGHLIGHT_COLORString with the color used for the highlighted text. May be any HTML-valid color; for example: 'white' or '#FFFF80'.'white'
HIGHLIGHT_BGString with color used for the background of the highlighted text. Any HTML-valid color.'blue'
ICONPATHThere are cases where you may want to separate the gif files into a directory just for images. For those cases use this variable to specify the location of the directory. Notes:
  • The value of this string should either by empty or terminated with a forward slash (/).
  • Relative paths are relative to the URL of the HTML page holding the tree.
Any valid URL that points to a directory (as opposed to a file.) Examples: 'images/', 'http://www.x.com/y/', etc.'' (empty string)
PRESERVESTATEThe user changes the state of the tree in two ways: by opening and contracting folders, and by highlighting nodes (if HIGHLIGHT=1). Unless that state information is stored, reloading the tree will revert it to its original state. With this variable set to one, the Treeview engine (ftiens4.js) stores the appropriate information in cookies to make it available across page loads. With the variable set to 0 no cookies are used by the script.
Two typical scenarios that require the reload of the tree are: pages with a frameless layout (see USEFRAMES), and database driven applications.

If the structure of the tree may change between reloads (a new folder is added in a database-driven application, for example) the use of the PRESERVESTATE will require the nodes to have a constant means of identification. Without persistent ids the script may try to use the wrong id and show an error. See the section on external ids, below.

If the same site uses more than one Treeview tree, the PRESERVESTATE mechanism will also need the trees themselves to have ids. See the section on Treeview identification below.

0 -> no storage of "state" in cookies
1 -> preserve state upon reload
0
STARTALLOPENSpecify if, upon loading the page, the tree should be displayed with all folders expanded. Note that this may be convenient for small or medium sized trees but defeats the optimizations introduced for very large tree (trees with hundreds or thousands of nodes.) Naturally, this option should also not be used together with PRESERVESTATE.0 -> show only one level
1 -> expand all.
0
USEFRAMESSpecify whether the tree will be displayed inside a frame or in a regular frameless page. If a frameless layout is intended, this variable should be explicitly reset because special DHTML needs to be generated in those cases.0 -> frameless layout
1 -> tree is in its own frame
1
USEICONSSetting this variable to zero removes the icons from all entries in the tree. Note, however, that for folder the little +/- control button is not removed, only the icon with the folder image. 0 -> remove icons
1 -> display icons
1
USETEXTLINKSWhen an URL is associated with a node (folder or link) the icon of the node becomes clickable. This variable controls if the text of each node should also be clickable (be an hyperlink) or not.0 -> only the icons are clickable
1 -> the text is clickable too.
0
WRAPTEXTSpecify whether the text in each entry is allowed to wrap around into more than one line.
If you are basing your design on one of my demos that uses frames, do not forget to remove the nowrap setting from the style tag at the top of the left frame html file.
0 -> single line
1 -> multi-line
0


Hierarchical construction of nodes

The configuration files (demo*Nodes.js) in the downloaded ZIP have an initial section where some global variables are set (described above) and then a section for the actual creation of folders and links. Here we describe those tree-construction commands. The examples given are taken from the demoFrameset.html example.

1. Create the root folder. Use this command:

    foldersTree = gFld("<i>Demo</i>", "demoFramesetRightFrame.html")
The function gFld takes a name and an optional URL, and returns the folder. You can give any name to your root folder and to the other folders inside of it. Note how even some formatting (italics) was used in the example above. You can also add an IMG tag to place a small icon in the folder name (for example a "new!" icon.)

The URL must either be just a file name (for example: demoFramesetRightFrame.html) or an whole URL complete with protocol (for example: http://www.treeview.net/treemenu/demopics/beenthere_europe.gif).

To learn more about gFld, see the section below "The optional link of the folder icon."

2. Place folders inside other folders by using the function 'insFld([parent folder], [child folder])'. For example:
aux1 = insFld(foldersTree, gFld("Europe", "http..."))

3. To create a document link use the function 'gLnk'. It takes three arguments:

Target:
'R' opens in the right frame (a frame named basefrm),
'B' opens in a new window,
'T' opens in the current browser window, replacing the frameset if one exists,
'S' opens in the current frame, replacing the tree.
Note: the function is case sensitive; use uppercase.
(For more info on the "doc type" argument see the section below named "More about the gLnk function."

Title: Text to be displayed in the tree for that node. This text can include some simple HTML, such as enclosing formatting tags (I, B, DIV, etc.), or even an IMG tag to place a small icon in the node name (for example: a "new!" icon.)

Link: URL of the document (may be absolute or relative.) Do not enter other information in this string. Adding a target parameter or an event handler will not work.
4. To place the document inside the tree use the function 'insDoc([parentfolder], [document link])'.

Note: If you want to rename some of the files included in the .ZIP, you will have to take in account the file dependencies: you may want to rename demoFramesetRightFrame.html but then you will need to update both demoFramesetNodes.js and demoFrameset.html. The file demoFrameset.html itself (the one most exposed to visitors) can be renamed without any problems with dependencies. Do not rename any other file.

More about the gLnk function

The first argument of the gLnk function not only controls the target of the page (right frame, new window, etc.) but may also help in the construction of the link itself. After the character that controls the target (R,B,etc.), add an extra lowercase character to the string. This extra character will specify the protocol to be prepended to the URL. If you do this you may leave the protocol out of the string given in the third argument. Example:

    gLnk("Rh", "Right frame", "www.x.net/y/z.html"))
These are the protocols the Treeview applet may prepend automatically, if there is interest in keeping the configuration file as small as possible: h: http:// , s: https:// , f: ftp:// , m: mailto: .

The optional link of the folder icon

In terms of how you want the script to behave to the user, you may not want the action of clicking on the folder to open a page (on the right frame or on a separate page.) In this case you want the click on the folder to be similar to a click on the '+' sign.

The way you do this in the configuration file is by giving a special value to the second argument of the gFld function. In the example included with in the download, this is how the whole statement looks:
  aux1 = insFld(foldersTree, gFld("Test A", "javascript:parent.op()"))

The special argument used is javascript:parent.op(), which is a call to an empty function. If you just give the empty string as the argument the folder may not be "clickable" for older browsers.

If folders with the "javascript:parent.op()" argument are not working properly for you, check what changes you made to the demoFrameset.html document. You may change the names of the files or even change the structure of frames in your site, but in the end this function must be defined in the header section of the html file that defines the frameset immediately holding the demoFramesetLeftFrame.html page (or its substitute.)

Alternative API for large trees

If your tree has more than a thousand nodes, you are probably using server-side code to generate it. In that case the Treeview-configuration JavaScript generated by the server should use a different API from the one described in the previous sections. This alternative API, used for the creation of document links, speeds up even further the time it takes the tree to be rendered after a page-load. Since this API is harder to program with and since benefits are only noticeable for very large trees, the insDoc/gLnk API is the recommended one for small trees manually configured. For more generic information on building a Treeview with server-side code, please see the section "Server-side, dynamic creation of folders and links".

The function folder.addChildren enables the declaration and construction of all documents inside one folder in one single statement. Note that if the folder has subfolders, those must be built first and then passed to addChildren. Because of this order dependency, tree-configuration files that use the addChildren API are very different from those that use insFld and insDoc: they reverse the order of folder creation.

Example:

    fldChild = gFld("FChild", "linkfld1.html")
    fldParent = gFld("F", "linkfld2.html")
    fldParent.addChildren([fldChild, ["Doc", "link.html"]])
The user will see a folder "F" with two nodes inside: the sub-folder "FChild" and the document "Doc".

Notes:

  • addChildren is a method of the folder object. The folder must have been created before the method is called (second statement above.)
  • addChildren's only argument is a list of children. Each element in the list can either be a folder object or a sub-list of two strings: the label to use for a doc node, and the link to use with that node.
You can see this function being used in the Very-large-tree example and in the Dynamic, server-side example demos.

In order to specify a target for these links created with addChildren, use the GLOBALTARGET configuration variable (see table above.) The .addChildren API hides the construction of the document objects. However, it is still possible to operate on those objects to change properties such as xID and iconSrc, which are generically described elsewhere in this page. In order to get access to the document object, use the children array member of the folder object. For example:

    fldParent.children[0].xID = "foo"

Using the single quote character and the double quotes character with tree configuration code

The use of the ' and " characters always requires extreme care with any programming language, and specially so with code that performs multiple operations and interpretations of string values. The Treeview is no exception.

You can run into trouble with the Treeview engine (ftiens4.js) using these special characters in the following scenarios:

  • the node name includes one of these characters,
  • the HREF link is of the type javascript:function... and the function takes string arguments,
  • a string in the arguments of the javascript:function includes one of the special characters.

To address these use cases you will have to in some cases use the String.fromCharCode() function, in other cases "escape" the character by prepending a back slash, and in other cases "escape" the character and the back slash. The code below covers all these combinations, it creates folders and documents that use the strings jack's and db quote:":

foldersTree = gFld("jack's", 'javascript:alert("jack" + String.fromCharCode(39) + "s")')
   insDoc(foldersTree, gLnk("R", "jack\'s", 'javascript:alert(\\\'jack\\\' + String.fromCharCode(39) + \\\'s\\\')'))
   insFld(foldersTree, gFld("db quote:\"", 'javascript:alert("db quote:" + String.fromCharCode(34))'))
   insDoc(foldersTree, gLnk("R", "db quote:\"", 'javascript:alert(\\\'db quote:\\\' + String.fromCharCode(34))'))

The programmatic demo also contains examples of the techniques above and some other alternative ones.

Changing the icons in the tree

In the configuration file you can indicate what icon should be used with a particular folder or "doc". The frame-based layout example showcases this functionality (it works with frameless layouts too.) Check the last folder and the document it contains.

If you are replacing the icon of a folder, you will have to provide two icons: one for when it's open, and another for when it's closed. In the configuration file demoFramelessNodes.js included with the free download you can see how this is done:

    aux1 = insFld(foldersTree, gFld("Other Icons", "..."))
    aux1.iconSrc = ICONPATH + "diffFolder.gif"
    aux1.iconSrcClosed = ICONPATH + "diffFolder.gif"
ICONPATH is one of the Treeview JavaScript "environment variables" (see section "Options for layout, look-and-feel, and more".) If you are not setting this variable it may be omitted from the above statements.

If you want to have the icon for open and closed folders to be the same you can just assign the same pathname to both the iconSrc and iconSrcClosed attributes.

In the case of the "doc" node, only the iconSrc is applicable. Here's the code from the demoFramelessNodes.js example:

    docAux = insDoc(aux1, gLnk("B", "D/L Treeview", "..."))
    docAux.iconSrc = ICONPATH + "diffDoc.gif"
For the icon, you can use any gif file with these dimensions: width=16, height=22.


Giving external ids to nodes

Nodes are usually identified by their order in the tree. The first folder is number 1, the first item inside that folder is number 2 and so on. The PRESERVESTATE mechanism works by storing information associated with these ids. If the structure of the tree changes (nodes added or deleted during the same session of a visitor) these dynamic ids will change too, and that may make the PRESERVESTATE mechanism fail.

The solution to this problem is to make sure that the ids assigned to the nodes are ids that do not depend on the particular structure of the tree at any given point. The same is to say that these ids are static, not dynamic. Assuming that those ids can be found, the way to assign them to the nodes is through the xID attribute. Here's an example of how it may look (adapted from the demoLargeNodes.js):

    foldersTree = gFld("Root", "a.jpg")
    foldersTree.xID = "B8A4"
    aux1 = insFld(foldersTree, gFld("Folder 1", "b.jpg"))
    aux1.xID = "1A2"
    aux2 = insDoc(aux1, gLnk("R", "Doc 1", "c.jpg"))
    aux2.xID = "XYZ"
Important notes:
  • You either use xID with all nodes or with none. If you are using xID, you must assign a value to the root node: foldersTree.xID = ...
  • The value of the xID of one node should not depend on what other nodes exist in the tree; therefore, it is wrong to assign 1,2,3,4,... to each node from root to last leaf. If you don't expect the structure of the tree to change, then don't use xID, and the nodes will be automatically given these successive numbers.
If the structure of the tree can change during a visitor's session, it's likely because the tree is being driven by a server-side application, and behind that application there is probably a database. If that is the case, then the values to assign in the client JavaScript to the xID attribute are simply the database keys from the table where the nodes are coming.

Some additional notes:

  • The xID can either be a string or a number. The strings cannot contain any of the following characters:
    • ^ (if you need to be able to use this character, redefine the variable cookieCutter)
    • '
    • "
  • The PRESERVESTATE variable and, thus, the xID member are important to preserve both the open/closed state of folder nodes and the highligh state of nodes in general. If your tree does not require node highlighting, your work can be simplified: assign values only to the xID members of folders and not to the xID of "links".
  • Please keep in mind that the node ids must be not only unique inside a tree, but also, more importantly, constant across the reload of the tree page. Suppose that a tree changes upon reload: regardless of other folders being added or deleted, if Folder A had id "id5" it should still be tagged "id5" after the reload.
  • The capitalization of the variables and member names in JavaScript is important. If you use "xId", for example, it will NOT work.
Unique identification of each Treeview tree

If you have more than one tree in your site, and if you are using the PRESERVESTATE mechanism, you will need to give unique identifiers to each tree. This identifier will be used in the name of the cookie and will help the trees to keep their states separately. Here's an example of how the code in each configuration file of each tree (demo*Nodes.js) will look like:

    foldersTree = gFld("Three years", "demoLargeRightFrame.html") foldersTree.treeID = "t2" //t3, t4, etc.

Adding extra HTML to Folders and Documents

The text that tags folders and documents is given through the gFld and gLnk functions. There is some but not total flexibility in this text in terms of the usage of HTML. You can use tags for bold, italics, etc., or even include images, but you are limited by the fact that all that HTML is going to be part of a <a HREF>...</a> block.

A new member was added with version 4.3 of Treeview that allows for other text to be added between the icon and the item's text. The name of this member is prependHTML. (It is applicable both to folders and to "documents".) Currently this member is being used with pages that show a Checkbox Tree (see demos.)

As with other object members, prependHTML is set right after the object is created:
   newObj = insDoc(aux1, gLnk("B", "Item 5", "..."))
   newObj.prependHTML = "<td valign=middle>not part of link</td>"
or more to the point:
   newObj.prependHTML = "<td valign=middle><input type=checkbox id='CB1'></td>"

There is one important rule to be followed concerning the contents of the string prependHTML . For compatibility with older browsers, the tree is all built with tables, where each "row" (a folder or a document) is a TR. For this reason the text used in prependHTML must always start and end with the delimiters of a TD block.

It is also important to either use STARTALLOPEN or BUILDALL. All the FORM elements contained in the tree must be created when the page is loaded for the FORM to include them.

Other details about the Treeview API

Nodes in the tree, folders or documents, are internally represented by Javascript objects, even before the tree starts to be rendered in HTML. These objects should not be confused with the DOM objects they generate. One Treeview Folder object, for example, will generate several DOM objects (images, text, etc.) once the tree is rendered.

If you give external ids to the nodes in the tree (see section "Giving external ids to nodes") you will be able to obtain a node object by calling the function myNode = findObj(id).

Once you have a Javascript variable with a reference to a Treeview node, there are several things you can do with it. You can for example highlight it by calling the function highlightObjLink(myNode). You can also find the parent of a node (corresponding to the folder holding that node) by querying the member myNode.parentObj.



Server-side, dynamic creation of folders and links (optional)

If you would like your server to automatically create a tree showing files and directories in that server's hard drive or in that server's local network, we have built a web site just for you: www.WebFileBrowser.com.

If you want information about using Treeview JavaScript to let your visitors browse the contents of a database, read on.

Before you attempt any server-side coding with Treeview, it is important that you read the previous two sections: A typical tree-holding page and Advanced Config. The dynamically generated tree will be contained in a page with the same general structure of a static tree and it will be built by using a sub-set of the functions and configuration variables here described.

Your next step should be to look at the code of the dynamic demo included in the free download ZIP (demoDynamic*.*). As you can see in this code, the .asp file is fulfilling two roles: it generates the regular HTML typical of a page that contains a tree, and it also generates the JavaScript that is typically found in a separate, static demo*Nodes.js configuration file (in the case, the .addChildren variant.)

In order to generate the necessary gFld and gLnk statements, the outputJavascript function in the demoDynamicLeftFrame.asp file queries the database. Please note how each call to response.write is terminated by a new-line character. It is a common mistake to forget the new-line characters between two JavaScript statements generated dynamically.

This code should provide you with a good starting point, even if your project neither uses ASP nor Access databases.




Akku | Calling Cards | Abrf Audio Books | Webdesign Und Suchmaschinenoptimierung | Electronic Parts | Zappos Shoes | Daily Coupon codes |