Make HTML Tables Sort-Able with Sorttable Javascript

Even though the web-design community has slowly been gravitating away from html tables the last decade since CSS3 really took off along with HTML4 and ultimately HTML5, html tables still have some very good uses – their true original use; displaying tabular data, you know.. tables.

Here’s an example of some tabular data in the form of imaginary Employees, wages, and start/end dates.

Name Salary Extension Start date Start date (American)
Bloggs, Fred $12000.00 1353 18/08/2003 08/18/2003
Turvey, Kevin $191200.00 2342 02/05/1979 05/02/1979
Mbogo, Arnold $32010.12 2755 09/08/1998 08/09/1998
Shakespeare, Bill $122000.00 3211 12/11/1961 11/12/1961
Shakespeare, Hamnet $9000 9005 01/01/2002 01/01/2002
Fitz, Marvin $3300 5554 22/05/1995 05/22/1995

Nice table right? Would be even nicer if columns could be sorted! For a long time the only way to achieve that would have been with url parameters and page refreshes. Who has time for that antiquated mess? Not Me.

Surely there is a better option for sortable HTML Tables?

Name Salary Extension Start date ▾ Start date (American)
Shakespeare, Bill $122000.00 3211 12/11/1961 11/12/1961
Turvey, Kevin $191200.00 2342 02/05/1979 05/02/1979
Fitz, Marvin $3300 5554 22/05/1995 05/22/1995
Mbogo, Arnold $32010.12 2755 09/08/1998 08/09/1998
Shakespeare, Hamnet $9000 9005 01/01/2002 01/01/2002
Bloggs, Fred $12000.00 1353 18/08/2003 08/18/2003

If you haven’t already noticed, the table above has columns that can be sorted by clicking the column header. You should also notice that rather than sorting alphanumerically, the date and numeric columns all sort properly too.

So, How Does One Accomplish Such Wizardry with Sortable HTML Tables? With “Sorttable”!?

  1. Download
    sorttable.js
  2. Include
    sorttable.js, by putting a link to it in the HEAD of your page, like so:
  3. Mark your table as a sortable one by giving it a class of “sortable”:
    Note that the library’s JavaScript file is called
    sorttable
    (two Ts), but the class you add to the table is
    sortable
    (one T).

That’s it! Tables with the ‘sortable’ class will have sortable columns via column header clicks. For aesthetic reasoning you may want to add the following styles to your stylesheet, or something similar and to your liking:

For advanced usage of Sorttable, check out the creator’s guide over at Kryogenix.org where you can also give the creator a tip for his valuable time and javascript!