}
sort-table.js is a pure JavaScript (no dependencies) solution to make HTML Tables sortable.
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:
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 |
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 |
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.