Cross browser table sorting with JavaScript

Demo page
sorttable.js revision 2, 2005-05-26
up.gifdown.gif

Usage

Download the .js file and the two .gifs and upload them to your web server

Include the script like this in your <head>:

<script type="text/javascript" src="sorttable.js"></script>
(adjusting for the correct directory, like src="../path/to/sorttable.js")

Make tables sortable by giving them the attribute class="sortable" (or "sortable" as one of multiple classes like class="myfirstclass sortable mythirdclass").

If you have other things happening on page load, such as <body onload="doSomething()">, add a call to the sorttable_init() function like this: <body onload="doSomething(); sorttable_init()"> If not, the script will start up by itself.


Details

The script assumes the column headers that it should make clickable will be either:

If you want to exclude a column from being sortable, add class="nosort" to the appropriate column header: <th class="nosort">

If you want the script to presort on page load (which you should rather do serverside, but hey), add presort="direction" to the appropriate column header, where direction is either asc or desc: <th presort="desc">

There are three datatypes by which this script can sort, which it attempts to automatically detect by analyzing the content of the first row of each column:

If you want to force a special datatype on a column (for example because you have several different datatypes in the same column on different rows), add a datatype="type" attribute to the appropriate column header, where type is either 1 for numbers or $ for currency (text is the default, so there is no attribute necessary for that): <th datatype="$">price</th>

If you want to adjust the arrow graphics, edit their filenames or paths in the first lines of the .js file like this: var sorttable_uparrow = '../path/to/mycustomuparrow.gif';


Style

The script adds various CSS classes that you can use:


Compatibility

Tested and working fully as expected in:

Usable in:

Believed to degrade gracefully in older browsers.


Christopher Clay 2005, loosely based on less compatible http://www.kryogenix.org/code/browser/sorttable/
This code is believed to be in the public domain.