Minimal Table Sorting Plugin - jQuery Sortberg.js

File Size: 5.74 KB
Views Total: 224
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Minimal Table Sorting Plugin - jQuery Sortberg.js

Sortberg.js is a lightweight and fast jQuery table sorting plugin that automatically selects the appropriate sorting method (order by or ascending by) based on the data value and supports complex tables with rowspan/colspan.

See Also:

How to use it:

1. Download and load the jquery.sortberg.js after jQuery.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/jquery.sortberg.js"></script>

2. Call the function sortberg on the HTML table and the plugin will do the rest.

<table>
  <thead>
    <tr>
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
  </tbody>
</table>
$(function(){
  $('table').sortberg();
});

3. It also supports grouped data as follows:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Alice</td>
      <td>+1 234-567-8901</td>
    </tr>
    <tr class="grouped">
      <td colspan="2">Additional Info For Alice</td>
    </tr>
    <tr>
      <td>Bob</td>
      <td>+1 987-654-3210</td>
    </tr>
    <tr class="grouped">
      <td colspan="2">Additional Info For Bob</td>
    </tr>
  </tbody>
</table>
$(function(){
  $('table').sortberg({
    // default: 'details'
    groupClass: 'grouped'
  });
});

4. Determine whether to ignore case sensitive. Default: false.

$(function(){
  $('table').sortberg({
    ignoreCase: true,
  });
});

5. Add your own sorting logic.

var myLogic = function(a, b){
  return $(a).data('specialdata') - $(b).data('specialdata');
};

$('table').sortberg({
  comparator: myLogic
});

Changelog:

2022-08-03

  • Only sort columns when clicking the th element, not when clicking child elements inside the th element

This awesome jQuery plugin is developed by kaptajnen. For more Advanced Usages, please check the demo page or visit the official website.