SorTable: Sorting table content with Javascript
On page load the following features are added to the table below.
Sorting: Clicking on the column headers will sort the body of the table. Successive clicking will alternate the order of the sorting.
Greenbar: The alternating white and blue rows are rendered to make the table more readable, and are redone with each table sort.
Ruler: Moving the mouse over a row in the body of the table highlights that row for additional ease of use in selecting items.
| Title | Author | Year | Price | |
| Harry Potter and the Philosopher's Stone | J K Rowling | 1997 | $12.95 | |
| Harry Potter and the Chamber of Secrets | J K Rowling | 1998 | $16.95 | |
| Harry Potter and the Prisoner of Azkaban | J K Rowling | 1999 | $18.95 | |
| Harry Potter and the Goblet of Fire | J K Rowling | 2000 | $24.95 | |
| The Gunslinger - The Dark Tower 1 | Stephen King | 1982 | $12.95 | |
| The Waste Lands - The Dark Tower 3 | Stephen King | 1991 | $16.95 | |
| Wizard and Glass - The Dark Tower 4 | Stephen King | 1995 | $19.95 | |
| Total | $75.05 | |||
The code is quite unobtrusive. A javascript file for each of the functions above is added to the file and any tables needing the above features are given an appropriate class.
The sorting code turns the header row into links and also tests for an appropriate sort method for the contents of the column in question. This is important as numeric fields must be sorted in numeric order, not alphanumeric order.
Columns can be excluded from the search and cells given a different sort value from the display value through optional attributes.
The sort functionality is a modified verson of Stuart Langridge's code. My main additions have been to rework it to use the structure of THEAD, TBODY and TFOOT tags and to get it to work with the alternating colours of greenbar.