About This Product
Metachecker.net | TrafficChecker.net | RankChecker.net
| Over 5000 Free Fonts | Tutorials | Javascript Forum | Other Javascript Resources | Cheat Sheet

Table Sorting is a curtesy of WebFX
See Original Here

[Tell A Friend]

Previous methods of table sorting have been in using data binding methods in IE4. With the new DOM Level 1 method you can now use both IE5 and Netscape Navigator 5. The method used is actually a sorting algorithm used as a standard sort method of the JS array that enables it to be faster. Click on this, demo

The sort method

The sort method uses a built in Array object in JS, whether you use it with or without an argument you will get the same result. In this particular situation the argument is a function that is used for means of comparison. A function that compares the inner text of two nodes is used because the '>' operator is not defined here.

Higher order functions

This takes functions as arguments or just returns a simple function. Since JS is object oriented, the entire thing is the object; even the functions that are used can easily be passed as functions as arguments. If you want to pass a function as an argument you then use the name without any parenthesis or you can create a new function object using the function constructor. Look below:

var myFunction = new Function("x","return x*x);");

function anotherFunction(x) {
	return x+x;

var mySecondFunction = anotherFunction;

It is now possible to pass these functions as an argument to a function that takes three functions as an argument and it looks kind of like this:

function strangeFunction(f1, f2, f3) {
	function f(x) {
		return f1(f2(f3(x)));
	return f;

strangeFunction(myFunction, anotherFunction, mySecondFunction)(5);
// gives 400

Compare function

Since you now know everything about the higher order functions, I can show you how to define compared functions. Because I wanted to sort by column and also by ascending and descending order I created a function that uses two arguments, the column number and a Boolean value for the sort order. This function returns another function that is used for comparisons.

function compareByColumn(nCol, bDescending) {
	var c = nCol;
	var d = bDescending;

	function _compare(n1, n2) {
		var v;
		if (getInnerText(n1.cells[c]) < getInnerText(n2.cells[c]))
			v = (d) ? -1 : +1;
		else if (getInnerText(n1.cells[c]) > getInnerText(n2.cells[c]))
			v = (d) ? +1 : -1;
			v = 0;

		return v;

	return _compare;

// And the calling looks like this

Next step

We now need to get the contents of the table into an array that can be sorted and can later be inserted into the table again.

Defining the sort
Manipulating the DOM tree
Demo and instructions how to use it in your pages
Sorting with behaviors