Logo
doctype [?]
[strict] [loose] [none]

jQuery Tips


Purpose

This page lists some tips, tricks, and code samples for the jQuery Javascript Framework. It very well may duplicate solutions found elsewhere, but will focus on things that I have found very useful or interesting.


Table Of Contents

  1. jQuery Cheat Sheet
  2. Expandable "Detail" Table Rows
  3. Simple Tree Structure

JQuery Cheat Sheet

A few different versions of my jQuery Cheat Sheet are available here.

Expandable "Detail" Table Rows

A common UI is to have a table of data rows, which when clicked on expand to show a detailed breakdown of "child" rows below the "parent" row.

The only requirements are:

  1. Put a class of "parent" on each parent row (tr)
  2. Give each parent row (tr) an id
  3. Give each child row a class of "child-ID" where ID is the id of the parent tr that it belongs to

Example Code
$(function() {
	$('tr.parent')
		.css("cursor","pointer")
		.attr("title","Click to expand/collapse")
		.click(function(){
			$(this).siblings('.child-'+this.id).toggle();
		});
	$('tr[@class^=child-]').hide().children('td');
});
Example Table (click a row)

ID Name Total
123 Bill Gates 100
  2007-01-02 A short description 15
  2007-02-03 Another description 45
  2007-03-04 More Stuff 40
456 Bill Brasky 50
  2007-01-02 A short description 10
  2007-02-03 Another description 20
  2007-03-04 More Stuff 20
789 Phil Upspace 75
  2007-01-02 A short description 33
  2007-02-03 Another description 22
  2007-03-04 More Stuff 20

Simple Tree Structure

There is a TreeView plugin for jQuery, and I've even written my own Tree Library to convert plain HTML unordered lists into a expandable/collapsable tree structure.

But using a <UL> list as the basis for a tree has some issues that can be easily overcome by using just a DIV-based structure. Although this doesn't have the advantage of maintaining the semantic markup of a UL list, if you are creating a web application for Javascript is known to be enabled, for example, that may not be a concern. This approach may be easier and work better.

Example Code
$(function() {
	$('div.tree div:has(div)').addClass('parent'); // Requires jQuery 1.2!
	$('div.tree div').click(function() {
		var o = $(this);
		o.children('div').toggle();
		o.filter('.parent').toggleClass('expanded');
		return false;
	});
});
Example CSS
div.tree div {
 padding-left:16px;
}
div.tree div.parent div {
 display:none;
 cursor:default;
}
div.tree div.parent {
 cursor:pointer !important;
 background:transparent url(plus.gif) no-repeat top left;
}
div.tree div.expanded {
 background:transparent url(minus.gif) no-repeat top left;
}
Example Tree

Item 1
Item 1.1
Item 1.2
Item 1.2.1
Item 1.2.2
Item 1.2.3
Item 1.3
Item 2
Item 2.1
Item 2.2
Item 2.2.1
Item 2.2.2
Item 2.2.3
Item 2.3
Item 3
Item 3.1
Item 3.2
Item 3.2.1
Item 3.2.2
Item 3.2.3
Item 3.3