table-sorter

@eydun/table-sorter

A lightweight, dependency-free ES module that adds sortable behavior to HTML tables.

Features

Installation

Install from npm:

npm install @eydun/table-sorter

Or copy src/table-sorter.js into your project.

Quick Start

<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>

API

Entry point:

import { tableSorter } from '@eydun/table-sorter';
tableSorter(target).init();

target can be:

Examples:

// 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();

HTML Attributes

Sorting Behavior

Accessibility

Sortable headers get:

Persistent Sort State

Sort 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.

Demo

See demo/index.html for a full example covering:

Browser Support

Modern browsers:

(Internet Explorer is not supported.)

License

MIT. See LICENSE.