A lightweight, dependency-free ES module that adds sortable behavior to HTML tables.
Shift+clickdata-sort-dateformatdata-sort-typelocalStorageTab + Enter / Space)Install from npm:
npm install @eydun/table-sorter
Or copy src/table-sorter.js into your project.
<table id="myTable">
<thead>
<tr>
<th data-sort>Name</th>
<th data-sort>Age</th>
<th data-sort>City</th>
</tr>
</thead>
<tbody>
<tr><td>Alice</td><td>30</td><td>Paris</td></tr>
<tr><td>Bob</td><td>22</td><td>London</td></tr>
</tbody>
</table>
<script type="module">
import { tableSorter } from '@eydun/table-sorter';
tableSorter('#myTable').init();
</script>
Entry point:
import { tableSorter } from '@eydun/table-sorter';
tableSorter(target).init();
target can be:
'#myTable', '.sortable-table', 'table[data-sortable]')<table> elementNodeList / HTMLCollectionExamples:
// Single table by id
tableSorter('#myTable').init();
// All tables by class
tableSorter('.sortable-table').init();
// Any selector
tableSorter('table[data-sortable]').init();
// Single DOM element
const tableEl = document.getElementById('myTable');
tableSorter(tableEl).init();
// Mixed multi-target init in one call
tableSorter(['#usersTable', '#ordersTable', '.team-table']).init();
data-sort on <th>:
<th data-sort>), current column index is used.<th data-sort="2">), explicit column index is used.data-sort on <thead>:
<thead>.data-no-sort on <th>:
<thead data-sort> is used.data-sort-dateformat on <th>:
DD, D, MM, M, YYYY, YY.<th data-sort data-sort-dateformat="DD/MM/YYYY">Start</th>data-sort-type on <th>:
number, text, date.<th data-sort data-sort-type="number">Amount</th>data-sorter-id on <table>:
id.Shift+click to add/toggle secondary and tertiary sort rules.data-sort-type overrides auto-detection for its column.Sortable headers get:
tabindex="0"aria-sort updates (none, ascending, descending)Enter and SpaceSort state is stored per table id:
localStorage['sorter-sortOrders-<table-id>']
On init, the sorter restores saved state if valid. Invalid saved payloads are ignored safely.
See demo/index.html for a full example covering:
data-no-sortdata-sort-typeModern browsers:
(Internet Explorer is not supported.)
MIT. See LICENSE.