sortable-tablesort

repository·main·Indexed 19 days ago

https://github.com/tofsjonas/sortable

A tiny, vanilla JavaScript table sorter (version 4.1.7) that attaches event listeners to tables with the 'sortable' class. It offers a lightweight version for standard use and a full-featured version (sortable.auto.js) with auto-initialization, Mutation Observer support for dynamic tables, and built-in accessibility. Features include custom sort values via data-sort, tiebreakers, sticky headers, and the ability to keep empty rows at the bottom.

Tokens
6.2K
Snippets
26
Records
29
Agent score
68%

What's inside sortable-tablesort

  1. Sort on a different column using `data-sort-col`

    main

    If your table uses colspan in the header, you can specify which column should actually be used for sorting when a specific header is clicked by using the data-sort-col attribute on the <th> element. The value should be the index of the target column.

    <thead
      <tr>
        <th"></th>
        <th">Category</th>
        <th class="show_name">Show</th>
        <th colspan="2">Overall</th>
        <th colspan="2" data-sort-col="5">On Our Dates</th>
        <th data-sort-col="7">First Sold Out</th>
      </tr>
    </thead>
  2. Handle Mutation Observer with nested elements

    main

    The sortable.auto.js mutation observer only triggers when a table is added directly to the DOM. If you wrap a table in a container (like a div), ensure the container itself is added to the DOM before the table is appended to the container, or ensure the container's addition triggers the observer correctly.

    Correct pattern for dynamic insertion:

    const div = document.createElement('div')
    // 1. Add the container to the DOM first
    document.body.appendChild(div)
    // 2. Then add the table to the container
    div.appendChild(table)
  3. Set a tiebreaker with `data-sort-tbr`

    main

    To define a secondary sort column used when values in the primary column are equal, use the data-sort-tbr attribute on the <th> element. The value should be the index of the tiebreaker column.

    <table class="sortable asc">
      <thead>
        <tr>
          <th data-sort-tbr="1">Year</th>
          <th>Month</th>
          <th>Day</th>
        </tr>
      </thead>
      <tbody>
        <tr><td>2010</td><td>07</td><td>25</td></tr>
        <tr><td>2010</td><td>11</td><td>12</td></tr>
      </tbody>
    </table>
  4. Perform alternative sorting with `data-sort-alt`

    main

    By holding Shift or Alt while clicking a table header, you can trigger an alternative sort order defined by the data-sort-alt attribute on the <td> elements.

    <table class="sortable">
      <thead>
        <tr>
          <th">Movie Name</th>
          <th">Size</th>
        </tr>
      </thead>
      <tbody>
        <tr data-sort-alt="c" data-sort="a">A</tr>
        <tr data-sort-alt="b" data-sort="c">B</tr>
      </tbody>
    </table>
  5. Use custom sort values with `data-sort`

    main

    To sort by a value that differs from what is visible to the user (e.g., sorting by bytes instead of 'MB' or by a timestamp instead of a formatted date), use the data-sort attribute on the <td> element within the <tbody>.

    <table class="sortable">
      <thead>
        <tr>
          <th>Movie Name</th>
          <th>Size</th>
          <th>Release date</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Zack Snyder's Justice League</td>
          <td data-sort="943718400">900MB</td>
          <td data-sort="20210318">03/18/2021</td>
        </tr>
        <tr>
          <td>The Sound of Music</td>
          <td data-sort="1610612736">1.5GB</td>
          <td data-sort="19651209">12/09/1965</td>
        </tr>
      </tbody>
    </table>
  6. Choose between Lightweight and Full-Featured versions

    main

    Sortable offers two main flavors depending on your needs:

    Lightweight (sortable.js)

    • Best for: Most standard use cases.
    • Features: Basic sorting via event listeners. Minimal performance impact.
    • Accessibility: Not included by default; you must load sortable.a11y.js separately if needed.
    • Best for: Applications that dynamically add tables to the DOM or require automatic sorting on load.
    • Features:
      • Auto-initialization: Automatically finds and initializes all .sortable tables on page load.
      • Mutation Observer: Automatically initializes new .sortable tables added to the DOM after page load.
      • Auto-sort on load: Uses aria-sort attributes to sort columns immediately when the page loads.
      • Accessibility: Included by default.
    • Warning: Uses a Mutation Observer which can impact performance in DOM-heavy applications (e.g., React, real-time updates, or frequent animations).
  7. Configure auto-sort on load

    main

    When using the Full-Featured (sortable.auto.js) version, you can define the initial sort state of a column by adding the aria-sort attribute to a th element.

    Supported values:

    • aria-sort="ascending"
    • aria-sort="descending"
    <th data-sort="name" aria-sort="ascending">Name</th>
  8. Add sticky headers to sortable tables

    main

    If you are using the sortable.min.css (the full-featured version), you can make headers sticky by adding the sticky class to the <table> element.

    If you are using custom CSS, use the following:

    .sortable thead th {
      position: sticky;
      top: 0;
      z-index: 1;
    }
    <table class="sortable sticky">
      ...
    </table>
  9. How to add new benchmarks

    main

    If you are contributing to the repository and want to add new performance tests, follow these steps based on the benchmark type:

    1. Benchmark.js: Add new configurations to the configs array in benchmark.js.
    2. Playwright: Add new test cases to tests/benchmark.spec.ts with appropriate performance thresholds.
  10. Sort a table on load

    main

    Using the default package

    Manually trigger a click on the desired header after the window loads:

    window.addEventListener('load', function () {
      const el = document.getElementById('target-header-id')
      if (el) el.click()
    })

    Using the auto package

    Set the aria-sort attribute on the <th> you want to sort by initially:

    <th aria-sort="descending">Size</th>
  11. Install sortable via npm

    main

    Install the package using your preferred package manager:

    npm install sortable-tablesort
    # yarn add sortable-tablesort
    # pnpm install sortable-tablesort

    After installation, you can use it in your project in two ways:

    1. Reference files from node_modules in HTML:

    <link href="./node_modules/sortable-tablesort/dist/sortable.min.css" rel="stylesheet" />
    <script src="./node_modules/sortable-tablesort/dist/sortable.min.js"></script>

    2. Import directly in JavaScript:

    import 'sortable-tablesort/dist/sortable.min.css'
    import 'sortable-tablesort/dist/sortable.min.js'
    // OR for the full-featured version:
    import 'sortable-tablesort/dist/sortable.auto.min.js'
    npm install sortable-tablesort
  12. Disable sorting for specific columns

    main

    To prevent a specific table header from triggering a sort, use one of the following methods:

    Add the no-sort class to the th element.

    <thead
      <tr>
        <th class="no-sort">Role</th>
        <th>Name</th>
      </tr>
    </thead>

    Using CSS

    Disable pointer events on specific columns via CSS.

    /* Disable the first column in every sortable table */
    .sortable th:nth-child(1) {
      pointer-events: none;
    }

    Using td instead of th

    The event listener only triggers on th. Using a td for a header will prevent sorting, but this may impact accessibility and styling.