Minimal Table Sorting Plugin - jQuery Sortberg.js

File Size: 6.08 KB
Views Total: 772
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
});

6. Specify the value to sort using the data-sort-value attribute instead.

<tr>
  <td data-sort-value="100">100</td>
  <td>Maria Anders</td>
  <td>Germany</td>
</tr>
<tr>
  <td data-sort-value="50">50</td>
  <td>Maria Anders</td>
  <td>Germany</td>
</tr>

Changelog:

2023-12-16

  • Fix bug that caused automatic sort method detection to not take `data-sort-value` into account

2023-12-14

  • Add support for specifying the value to sort on using the data-sort-value attribute.

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.