Add sorting links to your tables. By using DHTML and JavaScript, the sorting operation is instantaneous and does not require any support from the server.
Click the column headers to sort the table:
Name | Gender | Score | |
---|---|---|---|
Brian | Male | 92% | info@example.net |
Lisa | Female | 82% | info@example.net |
Arthur | Male | 85% | N/A |
Zoltran | Male | 9% | zoltran@example.com |
Another example (with a custom date sorting function) can be found on the Moo Database browser.
<SCRIPT LANGUAGE='JavaScript1.2' SRC='tablesort.js'></SCRIPT>
If you aren't familiar with <THEAD> and <TBODY> blocks, it might help to view the source code for the demo on this page.
By default the arrows use the text-only character codes '▲', '▼' and ' ' ('▲', '▼' and ' '). If you wish to use graphical arrows (as in the demo above), download these three images: arrow-up.gif, arrow-down.gif, blank.gif then add these lines after the initial script import:
<SCRIPT LANGUAGE='JavaScript1.2'> TableSort.arrowNone = " <IMG HEIGHT=10 WIDTH=10 SRC='blank.gif' ALT=''>"; TableSort.arrowUp = " <IMG HEIGHT=10 WIDTH=10 SRC='arrow-up.gif' ALT='↑'>"; TableSort.arrowDown = " <IMG HEIGHT=10 WIDTH=10 SRC='arrow-down.gif' ALT='↓'>"; </SCRIPT>
If you create a table using DHTML after the page has loaded and want to add sorting links to it,
call TableSort.init('someTable')
where 'someTable' is the ID of the new table.
If you have a column (such as a date) which requires a sorting order other than 'case', 'nocase' or 'num', a new sorting mode can easily be added. Just create a new comparison function. See the three comparison functions at the end of the script for examples.
IE 5+ (PC), Firefox, Safari, Opera and Chrome perform flawlessly. IE 5 for the Mac has serious layout bugs so the script disables itself under this browser. Older browsers will simply show a static table without sorting links.
Obviously this approach is not suitable for tables which span multiple pages (e.g. results 1-50 of 300). A client-side sort can only sort the data currently available, not your entire server-side database.
Certain languages (such as Japanese) have sorting requirements which transcend the character code values of text. Proper i18n sorting would require implementation of the Unicode Collation Algorithm.