FF2+ IE6+ Opera9+

jQuery TreeView Menu (v1.4)

Author: Jörn Zaefferer

Description: jQuery TreeView Menu brings together all the most practical features requested in a Tree Menu into one awesome menu script. The markup for the menu is simply a HTML list before the script transforms it into a TreeView Menu that supports the following:

  • Three different ways to specify the initial state of the tree nodes:
    • 1) All collapsed by default
    • 2) All collapsed except ones with CSS class "open", or
    • 3) All expanded except ones with CSS class "closed".
  • Ability to specify that only one tree branch is open at any time, collapsing any previous open branches.
  • Two types of persistence supported:
    • 1) "Cookie" based, persisting last tree state before user navigates away from page.
    • 2) "Location" based, expanding the branch or node with an "href" value that matches that of the current page (location.href). This lets you expand a particular branch that corresponds to the current page.
  • Supports optional animation with variable speed.
  • Controls can be added that collapses, expands, or toggles all nodes within a tree.
  • Supports optional asynchronous loading of the tree, so inner branches are loaded on demand based on JSON data returned from the server.

Now this is a Tree Menu!

Demos

Demo #1:

Notes:

  • All nodes collapsed explicitly by default, though overwritten by persistence feature below.
  • Only one node allowed open at any time.
  • Animation disabled..
  • "Location" persistence enabled, causing the branch with an "href" value matching that of the current page (location.href) to be expanded by default. In the demo above, that is "Item 1.0.0".

Configuration code:

$("#navigation").treeview({
 collapsed: true,
 unique: true,
 persist: "location"
});

Demo #2:

Click here to add a New Folder node to the end of the existing tree

  • Folder 1
    • Item 1.1
  • Folder 2
    • Subfolder 2.1
      • File 2.1.1
      • File 2.1.2
    • File 2.2
  • Folder 3 (closed at start)
    • File 3.1
  • File 4

Notes:

  • No Nodes collapsed explicitly. "Folder 3" is manually closed then by giving its LI element a "closed" CSS class.
  • Animation enabled, speed is "normal".
  • "Cookie" persistence enabled, causing the current tree state to be persisted.
  • Dynamically adding a sub tree to the existing tree demonsrated.

Configuration code:

$("#browser").treeview({
 animated:"normal",
 persist: "cookie"
});

$("#samplebutton").click(function(){
 var branches = $("<li><span class='folder'>New Sublist</span><ul>" +
"<li><span class='file'>Item1</span></li>" +
"<li><span class='file'>Item2</span></li></ul></li>").appendTo("#browser");
 $("#browser").treeview({
  add: branches
 });
});

Demo #3:

  • Item 1
    • Item 1.0
      • Item 1.0.0
    • Item 1.1
    • Item 1.2
      • Item 1.2.0
        • Item 1.2.0.0
        • Item 1.2.0.1
        • Item 1.2.0.2
      • Item 1.2.1
        • Item 1.2.1.0
      • Item 1.2.2
        • Item 1.2.2.0
        • Item 1.2.2.1
        • Item 1.2.2.2
  • Item 2
    • Item 2.0
      • Item 2.0.0
        • Item 2.0.0.0
        • Item 2.0.0.1
    • Item 2.1
      • Item 2.1.0
        • Item 2.1.0.0
      • Item 2.1.1
        • Item 2.1.1.0
        • Item 2.1.1.1
        • Item 2.1.1.2
      • Item 2.1.2
        • Item 2.1.2.0
        • Item 2.1.2.1
        • Item 2.1.2.2
  • Item 3
    • Item 3.0
      • Item 3.0.0
      • Item 3.0.1
        • Item 3.0.1.0
        • Item 3.0.1.1
      • Item 3.0.2
        • Item 3.0.2.0
        • Item 3.0.2.1
        • Item 3.0.2.2

Notes:

  • All nodes collapsed explicitly by default.
  • Animation enabled, speed is "fast".
  • Tree state persistence off.
  • Toggle all links added, to easily expand, contract, and toggle all branches within the tree.

Configuration code:

$("#red").treeview({
 animated: "fast",
 collapsed: true,
 control: "#treecontrol",
 }
});

Directions

Directions: Simply download jquery.treeview.zip, and refer to the demo page for the full source of the above 3 demos.

Setting Up a Tree View on your page

The markup for a Tree View Menu on your page should simply be a valid HTML list with a unique ID and CSS class that styles it:

<ul id="mymenu" class="filetree">
"
"
<ul>

Then, transform it into a Tree View Menu by calling the function Treeview(), invoked when the page has loaded to ensure the menu exists at time of invocation code in bold):

$(document).ready(function(){

 $("#mymenu").treeview({
  collapsed: true,
  other options...
 });

});

Note the outer most container code in bold- always define your TreeView configuration code(s) inside it so they are invoked only when the page has loaded.

treeview() function options

The main Treeview() function used to render a tree supports the following options passed in as parameters, all of which are optional:

Parameter Description
animated: speed Sets the animation speed. Valid values are one of the strings "slow", "normal", "fast", or an integer representing milliseconds, such as 1000 for 1 second animation.

To disable animation, remove this option entirely.

collapsed: true|false Sets whether all nodes should be collapsed by default.

Defaults to false.

unique: true|false Sets whether only one tree node can be open at any time, collapsing any previous open nodes.

Defaults to false.

persist: "location|cookie" Persists the tree's expand/collapse state in one of two ways:
  1. "location": looks within all tree nodes with link anchors that match the document's current URL (location.href), and if found, expands that node (including its parent nodes). Great for href-based state saving.
  2. "cookie": Saves the current state of the tree on each click to a cookie and restores that state on page load.

To disable persistence, remove this option entirely.

cookieId: string The desired custom cookie name to use when persisting via persist: "cookie".

$("#mytree").treeview({
 persist: "cookie",
 cookieId: "rememberme"
});

Defaults to interval value when this option is not defined.

control: jQuery selector Specifies the HTML element(s) on the page that will contain links to collapse, expand, and toggle all nodes within the tree, in that order. The valid value is a jQuery selector, most commonly, "#mycontainerid", where "mycontainerid" should be the ID of the control element. For example:

The HTML:

<div id="masstoggler">
<a title="Collapse entire tree" href="#"> Collapse All</a> |
<a title="Expand entire tree" href="#"> Expand All</a> |
<a title="Toggle the tree below" href="#">Toggle All</a>
</div>

The configuration code:

$("#mytree").treeview({
 collapsed: true,
 control: "#masstoggler"
});

Order is important when specifying the toggler links within the control element- the first link will always be assigned the "collapse all" behaviour, the second link the "expand all" behaviour, and finally, the last the "toggle all" behaviour.

Make sure the option "unique: true" is NOT set when setting the "control" option, or the links will appear as if they are not working!

toggle: callbackfunction Callback when toggling a branch. Arguments: "this" refers to the LI element with its sub UL either shown or hidden. Works only with speed option set (set speed: 1 to enable callback without animations):

$("mytree").treeview({
 toggle: function() {
  var subul=this.getElementsByTagName("ul")[0]
  if (subul.style.display=="block")
   alert("You've opened this Folder!")
  }
})

To disable toggle, remove this option entirely.

add: jQuery selector Extends the tree with additional nodes by adding them somewhere within the existing tree (as specified by the jQuery selector), then refreshes the tree to account for the new nodes. The jQuery selector must point to node(s) within the tree that already exist.

The following defines a link (with ID "#samplelink) on the page that when clicked on adds a new folder branch to the top of an existing tree:

$("#sampletree").treeview({collapsed: true});

$("#samplelink").click(function(){
 var topbranch = $("<li><span class='folder'>New Sublist</span><ul>" +
"<li><span class='file'>Item1</span></li>" +
"<li><span class='file'>Item2</span></li></ul></li>").prependTo("#sampletree");

 $("#sampletree").treeview({
  add: topbranch
 });

});

Demo:

Add New Folder

  • Folder 1
    • Item 1.1
      • Item 1.1.1
    • Folder 1.2
      • Item 1.2.1
      • Item 1.2.2
      • Item 1.2.3
  • Folder 2
    • Item 2.1.1

Where the new branch gets added within the tree depends on the code in bold. Here are some examples:

//adds new branch to the very end of the entire tree
var bottombranch=$('new_branch_html').appendTo("#sampletree");

//adds new branch to the top of the first Folder ("Folder 1")
var folder1topbranch=$('new_branch_html').prependTo("#sampletree ul:eq(0)");

//adds new branch to the end of the folder UL with id="#mybranch"
var mybranchbottombranch=$('new_branch_html').appendTo("#sampletree #mybranch");

In other words, use a valid jQuery selector to identify the UL within the tree to add the new branch to.

prerendered: true/false If set to true, skips parsing of branches within the tree with explicit classes defined, or DIVs within three with class "hitarea". This makes the tree more obtrusive, but speeds up render times for large trees significantly. For branches that are not parsed by the script, it is up to you to manually define their initial states using CSS, as the script will not do this for you (ie: setting "collapsed: true" has no effect on these branches):

Portion HTML of a sample tree with prerendered enabled:

"
<li class="expandable"><div class="hitarea expandable-hitarea"></div><a href="#"><strong>Home</strong></a>
<ul style="display: none;">
<li><a href="?/enewsletters/index.cfm">Airdrie eNewsletters </a></li>
<li><a href="?/index.cfm">Airdrie Directories</a></li>
<li><a href="?/economic_development/video/index.cfm">Airdrie Life Video</a></li>

Defaults to false.

url: "source.php" If defined, starts with an empty tree, then asynchronously adds branches to the tree when requested based on data returned from the server (in JSON format), specifically the specified server side script (ie: "source.php").

Sample initial HTML Markup on page:

<ul id="asynctree">
</ul>

Sample configuration code:

$("#asynctree").treeview({
url: "source.php"
})

See "Async Treeview example" for more info on this option.

Specifying which branches within the tree should be expanded or contracted by default

When you define a TreeView Menu on your page, there are 3 ways in general to specify the initial states of the branches within it. To specify that all branches be collapsed by default, just define the "collapsed: true" option within the configuration code:

$("#navigation").treeview({
 collapsed: true,
 unique: true,
 persist: "location"
});

To specify that all branches be collapsed except particular ones, still define "collapsed: true" above, but inside the tree's HTML, insert the CSS class "open" inside the parent LI of the branch that should be explicitly open:

<li class="open"><a href="#">Folder 3 (open by default)</a>
 <ul>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
 </ul>
</li>
"
"

To specify that all branches appear as they normally would except for certain ones that should be collapsed by default, first, undeclare "collapsed: true" from the configuration code, then insert the CSS class "closed" inside the parent LI of the branch that should be explicitly closed:

<li class="closed"><a href="#">Folder 3 (open by default)</a>
 <ul>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
  <ll>Item 3.1</li>
 </ul>
</li>
"
"

Table Of Contents

This script consists of an index page plus 1 supplementary page:

Wordpress Users: Step by Step instructions to add ANY Dynamic Drive script to an entire Wordpress theme or individual Post