table
. The problem with it is that this element doesn’t have an API that allows you to sort its rows based on a certain criteria, such as the price from low to high.
As a consequence of this lack of API, several JavaScript libraries have been developed and published to address this issue. In this article I’ll introduce you to Tablesorter (actually a fork of it), a jQuery plugin for client-side table sorting.
What is Tablesorter?
Tablesorter by Rob Garrison is a fork of the original Tablesorter library developed by Christian Bach. Tablesorter is a simple jQuery plugin that provides dynamic row sorting based on the values of one or more given columns, and also offers the possibility to paginate tables created using the HTMLtable
element. As I mentioned in the introduction, this plugin helps in filling the gap for these often needed features that aren’t native in HTML. Being a client-side library, one of its main advantages is that our users don’t need to reload the page they’re visiting in order to sort the data. Besides, client-side sorting is often very fast unless there is a very large amount of data to sort.
What you’ll love about this library is its simplicity. In its most basic case you have to include the library and then call a method, called tablesorter()
, to provide the possibility to sort the data of a table. Finally, this plugin has extensive documentation that will help you in handling most of the situations you may encounter in your projects.
Now that you know what this plugin is all about, let’s see how you can use it in your website.
Getting Started with Tablesorter
To use Tablesorter you have to download it and include it in the pages where you intend to use it. You can obtain Tablesorter in a few different ways. The first is by visiting its GitHub repository, while the second is through the following Bower command.bower install jquery.tablesorter
This plugin is made of a main JavaScript file, other optional JavaScript files, and several themes. Once downloaded, you have to include one of the themes, that you can find under the “css” folder, as shown below:
<link rel="stylesheet" href="css/theme.default.css" />
In this case the code includes the “default” theme. You have to import the JavaScript file after the jQuery library:
<script src="path/to/jquery.js"></script>
<script src="js/jquery.tablesorter.min.js"></script>
There is one last step to perform before you’re ready to use Tablesorter in your website. You must assign the class tablesorter
to all the tables you want to use with the plugin. This is needed for styling purposes only but it’s something you really want to do, otherwise the theme won’t be applied. Although the plugin still works, your users won’t have any clue about the added features.
Adding the tablesorter
Class
There are two ways in which you can add the class to the tables of interest. The first, and simpler, is to manually add the class name in the HTML source. But what if you can’t access or modify the HTML source? In this case you can employ JavaScript to dynamically add it. Let’s say that you want to allow your users to sort the data of every table in the page. To do so, you can write code like the following and place it at the bottom of the page:
var tables = document.getElementsByTagName('table');
for (var i = 0; i < tables.length; i++) {
tables[i].className += ' tablesorter';
}
This gives you the widest browser compatibility possible. However, if you only need to support modern browsers, you can take advantage of the classList API and other methods to retrieve DOM elements like queryselectorall()
.
Using jQuery, the previous code can be shortened to:
$('table').addClass('tablesorter');
At this point we can call the method tablesorter()
to expose the sorting functionality. A minimal example use of the plugin is shown below:
$('table').tablesorter();
A Basic Demo
To let you see this plugin in action, we’ll use the following table:<table class="tablesorter">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Price (in dollars)</th>
</tr>
</thead>
<tbody>
<tr>
<td>The CSS3 Anthology, 4th Edition</td>
<td>Rachel Andrew</td>
<td>29.00</td>
</tr>
<tr>
<td>Instant jQuery Selectors</td>
<td>Aurelio De Rosa</td>
<td>13.26</td>
</tr>
<tr>
<td>Killer UX Design</td>
<td>Jodie Moule</td>
<td>29.00</td>
</tr>
<tr>
<td>Jump Start CSS</td>
<td>Louis Lazaris</td>
<td>19.00</td>
</tr>
</tbody>
</table>
Putting together the snippets listed so far, results in the following demo:
Click on the headers and you’ll see that your table is now sortable!
It’s worth mentioning that Tablesorter works on all standard HTML table
s, so you must use thead
and tbody
in the tables.
Setting a Default Order
Sometimes you want your unsorted data coming from the server to be shown already sorted based on a given criteria. Using Tablesorter this can be easily achieved by passing an object literal to thetablesorter()
method. This object literal can contain several options to configure the plugin to work in the way you need. A list of all the options available is reported in the official documentation
.
Let’s say that you want to sort all the tables on the page based on the values of the first column in descending order. To do so, you have to pass a sortList
property whose value is a 2D array where the first element represents the 0-based index of the column to sort and the second element is 1
for the descending order and 0
for the ascending order. Therefore to achieve the goal discussed you have to write:
$('table').tablesorter({
sortList: [[0, 1]]
});
This example can be expanded further by setting a multi-column order criterion. If you want to sort the table based on the values of the first column in descending order and the third column in ascending order, you can write:
$('table').tablesorter({
sortList: [[0, 1], [2, 0]]
});
A live demo that employs the previous example is shown below and also available as a JSFiddle:
Adding Stripes to the Table
To enhance the readability of your data you should use two different colors for your rows: one for the odd rows and the other for the even rows. With Tablesorter performing this task is ridiculously easy. All you have to do is add a property calledwidgets
to the configuration object passing a value of zebra
wrapped into an array:
$('table').tablesorter({
widgets: ['zebra']
});
Before we see the result of this code, I want to show something else.
Changing the Default Theme
If you want to change the default theme, you have to replace the CSS file with the one representing the theme you want. So, let’s say that you want to use the “blue” theme. You have to replace the line:<link rel="stylesheet" href="css/theme.default.css" />
With:
<link rel="stylesheet" href="css/theme.blue.css" />
Next, you have to inform the plugin of the change by setting in the configuration object a property called theme
with the value representing the name of the theme you want to use. In this case, because the “blue” theme was used, you have to write:
$('table').tablesorter({
theme: 'blue'
});
Before we see a live demo I want to introduce you one last feature: pagination.
Paging Data with Tablesorter
The pagination feature is provided by Tablesorter as an external plugin, so before we can employ it in our pages we have to include the relative JavaScript and CSS file. The pagination plugin is downloaded together with Tablesorter and both the files are located in a folder named “addons/pager”. Once you include these files in your page (remember that the JavaScript file must be included after the Tablesorter plugin), you have to set up the markup for the pager as reported below:<div id="pager" class="pager">
<img src="addons/pager/icons/first.png" class="first"/>
<img src="addons/pager/icons/prev.png" class="prev"/>
<span class="pagedisplay"></span>
<img src="addons/pager/icons/next.png" class="next"/>
<img src="addons/pager/icons/last.png" class="last"/>
<select class="pagesize" title="Select page size">
<option selected="selected" value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select class="gotoPage" title="Select page number"></select>
</div>
At this point you have to call the tablesorterPager()
method by specifying the wrapper containing all the elements of the page. Based on the previous markup, you have to write:
$('#my-table')
.tablesorter()
.tablesorterPager({
container: $('#pager')
});
An example of a table that uses the pager, has the default theme changed, and also employs the zebra stripe widget is shown below and also available as a JSFiddle:
Conclusion
In this article I introduced you to a fork of Tablesorter, a jQuery plugin plugin for turning a standard HTML table into a sortable table without page refreshes. This plugin can successfully parse and sort many types of data including linked data in a cell. By using this plugin you can also add pagination to your data so they are easier to read. In case you liked the idea but not the plugin and you want an alternative, I suggest you check out DataTables.Frequently Asked Questions (FAQs) about Tablesorter
How Can I Customize the Appearance of My Tablesorter?
Tablesorter allows you to customize the appearance of your tables through CSS. You can modify the table headers, rows, and cells to match your website’s theme. You can also add zebra striping to your table rows for better readability. To do this, you need to include the CSS file in your HTML document and then apply the classes to your table elements.
Can I Use Tablesorter with Pagination?
Yes, you can use Tablesorter with pagination. Tablesorter has a pager plugin that you can use to divide your table data into multiple pages. This is particularly useful when dealing with large data sets. The pager plugin provides options for customizing the number of rows per page, the pager layout, and the pager container.
How Can I Sort Columns in Descending Order by Default?
By default, Tablesorter sorts columns in ascending order. However, you can change this to descending order by setting the sortInitialOrder option to ‘desc’. This will make Tablesorter sort the columns in descending order when the page loads.
Can I Disable Sorting for Certain Columns?
Yes, you can disable sorting for certain columns in Tablesorter. To do this, you need to add the ‘sorter-false’ class to the header of the column you want to disable sorting for. This will prevent Tablesorter from sorting that column when the header is clicked.
How Can I Use Tablesorter with AJAX?
Tablesorter supports AJAX, which allows you to load data into your table dynamically. To use Tablesorter with AJAX, you need to use the ajaxProcessing and ajaxUrl options. The ajaxProcessing option is used to parse the AJAX data, while the ajaxUrl option is used to specify the URL of the AJAX data.
Can I Use Tablesorter with Multi-Tbody?
Yes, Tablesorter supports multi-tbody, which allows you to have multiple tbody elements in your table. This is useful when you want to group rows together under different headers. To use Tablesorter with multi-tbody, you need to set the widgets option to include ‘zebra’ and ‘group’.
How Can I Update the Table Data?
You can update the table data in Tablesorter by using the update method. This method will re-sort the table based on the current sort order and update the zebra striping. You should call this method whenever you add, remove, or modify rows in your table.
Can I Use Tablesorter with Fixed Headers?
Yes, you can use Tablesorter with fixed headers. Tablesorter has a stickyHeaders widget that you can use to make your table headers fixed. This is useful when you have a long table and you want the headers to remain visible as you scroll down the page.
How Can I Add a Search Filter to My Table?
Tablesorter allows you to add a search filter to your table through the filter widget. This widget provides a search box that you can use to filter the table rows based on the entered text. You can customize the search filter by using the filter widget options.
Can I Use Tablesorter with Bootstrap?
Yes, you can use Tablesorter with Bootstrap. Tablesorter has a Bootstrap theme that you can use to style your tables according to the Bootstrap framework. This theme includes styles for table headers, rows, cells, and pagination.
I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.