jQuery » treeView Effects

Purpose

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

This is version three. A simple list that gets enhanced, adding show/hide effects

Usage: class="tv"

$(document).ready(function(){
	$("ul.tv")
		.find("li:last-of-type").addClass("tvil").end()
		.find("li[ul]").addClass("tvic").swapClass("tvil", "tvilc").append("<div class=\"tvca\">").find("div.tvca").click(function(){
			$(this).parent("li")
				.swapClass("tvich", "tvie").swapClass("tvilch", "tvile") /* Collapsed */
				.swapClass("tvieh", "tvic").swapClass("tvileh", "tvilc") /* Expanded */
  			.find(">ul:visible").slideUp("normal").end()
  			.find(">ul:hidden").slideDown("normal").end();
  	}).each(function() {
			$(this).hover( 
				function() { $(this).parent().replaceClass("tvilc", "tvilch").replaceClass("tvic", "tvich").replaceClass("tvie", "tvieh"); },
				function() { $(this).parent().replaceClass("tvilch", "tvilc").replaceClass("tvich", "tvic").replaceClass("tvieh", "tvie");; }
			);
		});
});

$.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);
		}					
	});
};

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

/* 
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.


Myles Angell
June 22nd, 2006