Sun 6 Nov 2005
The principle of unobtrusive javascript has been around for a while, and the old sortable html table thing has been used all over the place. This version has been updated to
- work with tables that use thead and tbody to separate header rows from content rows,
- works with tables that use odd/even styling for the data rows,
- it has a fix for Safari browsers,
- and it can use different sort types instead of the built in Javascript sort. Notably, the merge sort is
a stable sort that is pretty fast.
So, cut to the chase, I hear you saying. Alright. Here is a table to play with.
| Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 |
|---|---|---|---|---|---|---|
| 1 | a | blue | Gamma | $1.23 | 12-25-2001 | 23 Skidoo |
| 2 | b | blue | Delta | $10.23 | 10-25-2001 | 45 Skidoo |
| 3 | c | green | Rho | $100.23 | 12-01-01 | 23 Skidoo |
| 4 | d | red | Rho | $1.23 | 12-01-99 | 23 Lettermen |
| 5 | e | yellow | Gamma | $1.45 | 12-01-1999 | 123 Bucklemyshoe |
| 6 | f | red | Alpha | $1.54 | 07-15-2005 | 2 Pickles |
| 7 | a | yellow | gamma | $1.00 | 07-15-2005 | 12 Dozen |
| 8 | b | green | alpha | $23.00 | 07-15-05 | 12 Dozen |
| 9 | c | blue | delta | $23.00 | 12-25-2001 | 23 Lettermen |
| 10 | d | blue | rho | $23.00 | 07-15-2005 | 23 Skidoo |
| 11 | e | green | pi | $1.23 | 11-25-2003 | 1 Way |
| 12 | f | orange | Pi | $2.23 | 11-25-2004 | 37 Signals |
The reqiurements for using this are:
- Give your table an id attribute
- Give your table a class sortable
- Use thead and tbody in your table for header and body rows
- Include the sorttable.js javascript in the head of your document
- Optinally grab the sorttable.css and include it as a starting point for your stuff.
What, you were expecting more steps? Well you can set the sort type, change the
arrows, add odd-even styling to the rows and more. UTSL for that, man.
This page also includes a nice little trick to do logging when in a sort of debug mode.
To turn on the logging, you just include a textarea on your page with an id of logarea.
Like this:
When the textarea is present, log messages will be added to it. When it’s not there,
nothing happens to the log messages.
Is there a way to run the sort function other than clicking in the headers?
I wish to be able to call the sort function based on other user inputs on the page.
Thanks in advance.
Sure, renerea. Just look at what happens in the onClick handler in the header and call that function from any other place you want!