jQuery » treeView Basic

Update!

Jörn Zaefferer has informed me that he has begun a rewrite of this for the latest version of jQuery. You can find it in the jQuery plugin repository: http://jquery.com/dev/svn/trunk/plugins/treeview/

Purpose

Create a nice expanding and collapsing tree view control using jQuery.

This is version one. A simple list that gets enhanced.

Usage: class="tv"

Update June 23rd, 2006:

Update July 10th, 2006: Changed .find("li:last-of-type") to .find("li:last-child")

Original Code

$(document).ready(function(){
	$("ul.tv")
		.find("li:last-child").addClass("tvil").end()
		.find("li[ul]").addClass("tvic").swapClass("tvil", "tvilc").append("<div class=\"tvca\">").find("div.tvca").toggle(
				function(){ $(this).parent("li").swapClass("tvic", "tvie").swapClass("tvilc", "tvile").find(">ul").slideUp("normal"); },
				function(){ $(this).parent("li").swapClass("tvic", "tvie").swapClass("tvilc", "tvile").find(">ul").slideDown("normal"); }
			);
});

$.fn.swapClass = function(c1,c2) {
	return this.each(function() {
		if ($.hasWord(this, c1)) {
			$(this).removeClass(c1);
			$(this).addClass(c2);
		} else if ($.hasWord(this, c2)) {
			$(this).removeClass(c2);
			$(this).addClass(c1);
		}					
	});
};

/* 
Code Highlighting 
Courtesy of Dean Edwards star-light 
http://dean.edwards.name/my/behaviors/#star-light.htc
	- with jQuery methods added, of course
*/

Sample Markup

Hard Coded HTML

Sample 1

Sample 2

PHP Generated Random

Some recursive PHP to randomly load variations.


These examples are here for your own learning. If you find yourself using part or all of them, give credit where appropriate. Enjoy!

Myles Angell
June 22nd, 2006