Make any HTML table sortable

See it in action #

Visit the codepen.

Usage #

Download sotable-min.js from GitHub and put that file into your HTML page.

HTML to embed sotable-min.js into a web page
<script src="sotable-min.js"></script>
addEventListener('load', () => sotable()); //activate sotable functionalty on load

To experiment and dive deeper, it´s best to clone the entire repository and investigate the index.html, which serves as an example. Sotable is also available as an npm package.

Install sotable npm package
npm i sotable
Use sotable npm package
const sotable = require('sotable');;

Function #

Sotable will query all tables on a web page and turn each table with <th> elements in the first table row into a sortable table. An explanation of the sort behavior will be added to the table <caption>. If the table doesn´t have a caption, it will be created.

Settings #

Sotable can run without any configuration, like in the example above. Nevertheless sotable can be called with a settings object.

Calling sotable with a settings object
<script src="sotable-min.js"></script>
//call sotable with a settings object
//the shown values are the default values
addEventListener('load', () => sotable({
indicatorAsc: 'ᐃ',
indicatorDsc: 'ᐁ',
sortHint: 'Sort the table by clicking on a column heading.',
restoreHint: 'Restore the original order by clicking <button>Restore Order</button>.',
whiteList: '',
blackList: ''
})); //activate sotable functionalty on load

Explanation of the settings:

Accessibility #

Many design decisions for proper accessibility of sotable stem from Sortable table columns by Adrian Roselli. Among those are

References #

Sotable is influenced by JavaScript Sort HTML Table, which has a neat way of leveraging selectors for sorting, like tr:nth-child(n+2). In this context, please refer to How nth-child works and :nth tester.

  1. Locating DOM elements using selectors ↩︎

  2. Generally, use buttons for performing an action on the site and use links for sending the user somewhere. Source: Six ways to make your site more accessible ↩︎