Minimal Table Sorter In JavaScript – table-sort.js

Category: Javascript , Table | April 15, 2021
Author: LeeWannacott
Views Total: 72 views
Official Page: Go to website
Last Update: April 15, 2021
License: MIT

Preview:

Minimal Table Sorter In JavaScript – table-sort.js

Description:

table-sort.js is a minimal table sorter that is easy to implement by simply add the CSS class table-sort to the table tag.

How to use it:

1. Download the library and insert the table-sort.js into the HTML page.

<script src="table-sort.js"></script>

2. Add the CSS class table-sort to your HTML table and the library will do the rest. Users can easily sort the table rows by clicking the table headers.

<table class="table-sort">
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

3. If you’d like to sort table rows in reverse order, just add the order-by-desc class to the th element.

<table class="table-sort">
  <thead>
    <tr>
      <th>Month</th>
      <th class="order-by-desc">Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

Changelog:

04/15/2021

  • Remove console log

04/12/2021

  • Refactoring: took DictOf off DictOfCoumnAndTableRow and put tr.querySelectorAll(td).item(columnIndex).innerHTML into a variable called tdInnerHTML
  • Refactor code and reuse values

You Might Be Interested In:


One thought on “Minimal Table Sorter In JavaScript – table-sort.js

  1. LeeWannacott

    Hey, thanks for writing the article.

    I made table-sort-js for my own use case when I needed to sort a table and other library’s required dependencies, multiple files or didn’t sort properly.

    The objectives of table-sort-js are:
    * Be easy to use (e.g Download one file and just put “table-sort” on table tags to make sortable).
    * No dependencies (No jQuery)
    * Be able to sort (dates, numbers, alpha, alphanumeric, etc.)(Properly; meaning natural sort)
    * Not interfere too much with CSS of tables that should be left to the user in my opinion. Although, I might change the pointer when a user moves over the column header to show it is interactive.

    I have also released table-sort-js on npm:
    You can use npm install table-sort-js and require(“../node_modules/table-sort-js/table-sort.js”)
    npm link: https://www.npmjs.com/package/table-sort-js

    Thank you.

    Reply

Leave a Reply