This tutorial walks through the creation and installation of an object-oriented JavaScript implementation of the QuickSort algorithm. This script is an extendable, unobtrusive, and cross-browser compatible way of enhancing almost any type of tabular data.
<script src="tsorter.min.js" type="text/javascript"></script>
function init() {
var sorter = tsorter.create('TABLE-ID');
}
window.onload = init;
That's it! Seriously, you can upload the files and sort your tables.
It's common to have numbers, text, links, or even inputs inside table cells. The script can handle sorting a number of built-in data types. Here are the defaults that come with it:
numeric | For sorting integers or floats |
input-text | For sorting <input> tags by value |
link | For sorting <a> tags by their textContent value |
Specify the data type for each column by putting a data-tsorter attribute on each <th> element.
<thead>
<tr>
<th>Column 1 - defaults to text comparison</th>
<th data-tsorter="numeric">Column 2 - Numbers</th>
<th data-tsorter="input-text">Column 3 - Inputs</th>
</tr>
</thead>
What if your table has custom HTML inside its <td> tags as in the example? Then we have to teach the script how to access the value we want to sort by. For a quick example consider a 3 column table that has one column whose values are wrapped in <a> tags, and one column that contains <img> elements like so:
<table id="result_table" class="sortable">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2 - Image Column with Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Cell Row 1</td>
<td><img src="images/category1.png"/>120</td>
</tr>
<tr>
<td>First Cell Row 2</td>
<td><img src="images/category2.png"/>256</td>
</tr>
...
</tbody>
</table>
First, we add an attribute to the target <th> cell which will tell our script that this column is filled with links.
<th data-tsorter="image-number">Column 2 - Image Column with Number</th>
tsorter.create('table-id', 0, {
image-number: function(row){
return parseFloat( this.getCell(row).childNodes[1].nodeValue, 10 );
}
});
Upload the scripts and refresh your page. If all has gone well you can now sort your custom data.
Sometimes you have two data tables on the same page. Luckily things scale well. Here is the JavaScript required to make two tables sortable.
function init()
{
var sorter1 = tsorter.create('TARGET_TABLE_ID');
var sorter2 = tsorter.create('SECOND_TARGET_TABLE_ID');
}
window.onload = init;