The script converts simple HTML data tables into sortable tables. It adds the necessary interactive elements, functionality and accessibility, ensuring that the table degrades gracefully if it needs to.
- Create a simple HTML data table.
- Put
class="sortable"on the<table>element. - Put
class="sortable-colum"on each<th>element. - Inside each
<th>element, put<span class="th-content">Column name</span>. - Inside each
<span class="th-content">put<i class="arrow!"</i>.
<table class="sortable">
<thead>
<tr>
<th class="sortable-colum">
<span class="th-content">Column title <i class="arrow"></i></span>
</th>
...
</tr>
</thead>
...
</table>
-
Use the
data-sortbyattribute on any<th class="sortable-column">to be sorted. Choose fromnumeric,date,text, ormoney. If thedata-sortbyattribute is not present, the script defaults tonumericas the sort criterion. -
Call the
sortable-table.jsscript from the end of the document.
<script src="sortable-table.js"></script>
</body>
</html>
The script:
- Sets
aria-sort="none"to each<th class="sortable-column">element. - Adds a
clickevent listener to each<th class="sortable-column">element. - Sets
role="button"andtabindex="0"to each<span class="th-content">element. - Adds a
keydownevent listener to each<span class="th-content">element, that listens for the space (keycode 13) and enter (keycode 32) keys. - Uses the
data-sortbyattribute to determine the sort criteria and sorts each column accordingly. - Sets the
aria-sortattribute toascendingordescendingas appropriate. - Updates the ```` element with the appropriate visual marker for the sort order.