Table Sorter

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 Email
Brian Male 92%
Lisa Female 82%
Arthur Male 85% N/A
Zoltran Male 9%

Another example (with a custom date sorting function) can be found on the Moo Database browser.


  1. Download tablesort.js (9KB) or the compressed tablesort-min.js (4KB), then add this line anywhere in your page:
      <SCRIPT LANGUAGE='JavaScript1.2' SRC='tablesort.js'></SCRIPT>
  2. Modify your table(s) so that the header row(s) are within a <THEAD> block, any footer rows are within a <TFOOT> block, and the main content is in a <TBODY> block.
  3. Add 'CLASS=case', 'CLASS=nocase' or 'CLASS=num' to the <TH> or <TD> cells which you want to turn into sorting links. These specify whether the column should be sorted alphabetically with case-sensitivity, alphabetically without case-sensitivity, or numerically. Note that if these cells already have classes you can assign multiple classes separated by spaces: CLASS="nocase navigation".

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 '&#x25b2;', '&#x25bc;' and '&nbsp;' ('▲', '▼' 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='&uarr;'>";
    TableSort.arrowDown = " <IMG HEIGHT=10 WIDTH=10 SRC='arrow-down.gif' ALT='&darr;'>";

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.

Last modified: 6 May 2011