}

Demo for sort-table.js

sort-table.js is a pure JavaScript (no dependencies) solution to make HTML Tables sortable.

Basic Usage

The basic table sorting functionality can be added simply by including sort-table.js anywhere in your document and adding CSS class 'js-sort-table' to all tables you want sortable. It works like this:

<table class="js-sort-table">
Row Strings Dates
1 Shoe 9/11/2001
2 Twine 12/7/1941
3 Thread 1/20/2008
4 Rope 9/17/1862
5 Yarn 8/6/1945
6 Nylon 7/4/1776

Advanced Styling

sort-table.js uses CSS classes to track its state. This allows for advanced styling by applying styles to the classes below.

Also demonstrated in the table below is the handling of thead-less tables. If no thead is found in the table, one will be created and the first row will be added to it.

Row CSS class Description
1 js-sort-table Apply this to the table to indicate sortability
2 js-sort-asc This is applied to the table when sorting ascending
3 js-sort-desc Likewise, this indicates descending sort
4 js-sort-0 The zero-based number of the sorted column
5 js-sort-string By default, string sorting is used, making this optional
6 js-sort-date When applied to a cell in the header, column will be interpreted as dates
7 js-sort-number This tells sort-table to treat the column as numbers
8 js-sort-last Set this class to a TH to sort by the last word in each cell
9 js-sort-input If your table has form inputs, this allows sorting by their value

Advanced Sorting

There are a few supported data types, and adding new ones is very simple. To indicate the data type a column should be sorted as, add its CSS class to the column's header (TH) tag. String sorting is the default type. Below are demonstrated the included types.

Multi-row headers use the last row
number number string (default) date last input
1 123 Shoe 9/11/2001 John Doe
2 21 Twine 12/7/1941 John Q Public
3 3 Thread 1/20/2008 John Smith
4 42 Rope 9/17/1862 Joe T Plumber
5 58 Yarn 8/6/1945 John
6 6 Nylon 7/4/1776 John Johnson

Manual calls to tableSort can be made,

  • such as this one that sorts descending by the second column:
  • or this one that re-sorts the table in the event that something else adjusted it: