Minimal Client-side Table Sorting Library – tableSortable.js

Category: Javascript , Table | February 28, 2022
Author:rpserjo
Views Total:302 views
Official Page:Go to website
Last Update:February 28, 2022
License:MIT

Preview:

Minimal Client-side Table Sorting Library – tableSortable.js

Description:

Table sorting is one of the most powerful features you can add to your HTML table, allowing users to alter the order of its rows. Many libraries include sorting as a feature, but all of them need complex dependencies such as jQuery.

tableSortable.js is a super tiny (less than 1kb) table sorting library that helps create and reorder HTML tables with minimal effort. The library has no dependencies and comes with clean, semantically correct, vanilla JavaScript under the MIT license.

How to use it:

1. Load the tableSortable.js library in the document.

<script src="tableSortable.js"></script>

2. Add the CSS class sortable to your HTML table and config the sorting behavior with the following attributes:

  • data-nonsortable: used to ignore a specific table column.
  • data-isint: determine whether to sort the table column is sorted as integer.
  • data-value: sort the table column by value. Useful for dates and times.
<table class="sortable">
  <thead>
    <tr>
      <td>Name</td>
      <td data-nonsortable="true">Alias</td>
      <td>City</td>
      <td>First Appearance</td>
      <td data-isint="true">Pos. in Empire top-list
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Bryce Wayne</td>
      <td>Batman</td>
      <td>Gotham</td>
      <td data-value="19390501">May 1939</td>
      <td>2</td>
    </tr>
    <tr>
      <td>Tony Stark</td>
      <td>Iron man</td>
      <td>New York</td>
      <td data-value="19630301">March 1963</td>
      <td>Unknown</td>
    </tr>
    <tr>
      <td>Clark Kent</td>
      <td>Superman</td>
      <td>Metropolis</td>
      <td data-value="19380418">April 18, 1938</td>
      <td>1</td>
    </tr>
    <tr>
      <td>James Howlett</td>
      <td>Wolverine</td>
      <td>Unknown</td>
      <td data-value="19741001">October 1974</td>
      <td>4</td>
    </tr>
    <tr>
      <td>Bruce Banner</td>
      <td>Hulk</td>
      <td>Unknown</td>
      <td data-value="19810101">1981</td>
      <td>-</td>
    </tr>
    <tr>
      <td>Piter Parker</td>
      <td>Spiderman</td>
      <td>New-York</td>
      <td data-value="19620801">August 1962</td>
      <td>5</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td></td>
      <td>non-sortable</td>
      <td></td>
      <td>sorted by value tag</td>
      <td>sorted as integer</td>
    </tr>
  </tfoot>
</table>

3. Customize the ASC & DESC indicator in the CSS:

table.sortable > thead > tr > td.order-asc:after{
  display: inline-block;
  text-align: center;
  width: 15px;
  content: '\25B2';
}
table.sortable > thead > tr > td.order-desc:after{
  display: inline-block;
  text-align: center;
  width: 15px;
  content: '\25BC';
}

You Might Be Interested In:


Leave a Reply