Sorting Tables with Object Oriented JavaScript QuickSort
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.
Working DemoResources
- JavaScript (5kb) or Compressed (3kb)
- Sample CSS
- Exchanging HTML Table Rows
Implementation
Code Documentation
Making your tables sortable
1. Download the JavaScript file
2. Include the external Javascript file in the document <head>
<script src="TSorter_1.js" type="text/javascript"></script>
3. The JavaScript to get things going
function init()
{
var Table1Sorter = new TSorter;
Table1Sorter.init('TARGET_TABLE_ID_VALUE');
}
window.onload = init;
That's it! Seriously, you can upload the files and sort your tables.
Extending the script
But what if your table has HTML inside its' <td> tags as in the example ? Well, then you will have to tell the script how to access those values. Don't worry though, you only have to tell it once. For a quick example we will consider a 3 column table that has one column whose values are wrapped in <a> tags, like so:
Table with a column of links
<table id="result_table" class="sortable" border="0" cellpadding="0" cellspacing="0" rules="none">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2 - Link Column</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Cell Row 1</td>
<td><a href="page.html">Second Cell Row 1</a></td>
<td>Third Cell Row 1</td>
</tr>
<tr>
<td>First Cell Row 2</td>
<td><a href="page2.html">Second Cell Row 2</a></td>
<td>Third Cell Row 2</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.
1. Add the abbr attribute to the <th>
<th abbr="link_column">Column 2 - Link Column</th>
Secondly, add a new case to the setGet function in TSorter_1.js
2. Extending the setGet function
function setGet(sortType)
{
switch(sortType)
{
case "link_column":
get = function(index)
{
return getCell(index).firstChild.firstChild.nodeValue;
};
break;
default:
get = function(index){ return getCell(index).firstChild.nodeValue;};
break;
};
}
Upload the scripts and refresh your page. If all has gone well you can now sort the link column also. Here are some more examples of accessing various DOM elements inside your table cells.
How about multiple tables on the same page?
Sometimes you have two data tables on the same page. Luckily things scale well. Here is the JavaScript required to make two tables sortable.
Making multiple tables sortable
function init()
{
var Table1Sorter = new TSorter;
var Table2Sorter = new TSorter;
Table1Sorter.init('TARGET_TABLE_ID_VALUE');
Table2Sorter.init('SECOND_TARGET_TABLE_ID_VALUE');
}
window.onload = init;