For one of my projects I wrote simple javascript code that sorts
table data. At some point I wanted to use the code for another
website, so I've made it generic enough to suit different websites.
Eventually I released the code under GPL. Since then I've made several
enhancements to the code, and now the table sorting script has the
following features:
Automatically adds links to column names.
Clicking on column name repeatedly switches sorting order to
ascending, descending and unsorted (original order).
Displays sorting order as an up or down arrow next to the column
name. The arrow character can be optionally replaced with another
character/string or an image.
Sorts column data containing plain text, HTML text (HTML is
stripped), integer numbers, floating-point numbers and dates.
Multi-column sort: The script remembers what columns were
selected before and their sorting order. When the script sorts the
data in primary (currently selected) column and finds that two rows
have the same column data, it uses data from previously
selected columns to determine the sorting order of columns.
Multi-table support: the script can sort data in any number of
tables on the page.
It is possible to specify initial sorting order.
Optionally saves the sorting order into cookie(s), and
automatically restores sorting order after the page is
reloaded.
Optionally applies zebra-striping to columns.
Example:
Current sorting order of the second table is stored in a cookie.
If you refresh the page the table will have exactly the same sorting order
as it had before refreshing. Also, the second table has custom sorting
up/down characters.
Please download a file gs_sortable.js (see links below) - this is
the only external
javascript file that you will need. Put it somewhere on your web server.
Do not link to original file on this server because:
You will be using my bandwidth, and I will not like it.
I may post updated version of the javascript file with the same name,
and this may break your pages.
If somebody breaks into my server it'd be easy for them to modify the
file and do some nasty things to your page, like getting user cookies
for your domain, or redirecting all users from your page to some other
page.
Add id="some_name" to the table that you want to sort:
<table id="my_table">
... more HTML data ...
"some_name" id should be unique (it's an HTML requirement).
Put "<thead>" and "</thead>" tags around the table row that contains column names, like this:
<table id="my_table">
<thead>
<tr><th>Name</th><th>Year</th></tr>
</thead>
... table data ...
</table>
You don't necessarily need to use TH tags for that row - TD will work too.
Add javascript code to your page:
<script type="text/javascript" src="/gs_sortable.js"></script>
<script type="text/javascript">
<!--
var TSort_Data = new Array ('my_table', 's', 'i', 'f');
tsRegister();
// -->
</script>
"tsRegister();" is optional if you want the script to handle only one
table on the page, and required if you want to add column sorting to
more than one table. The part that you need to change in this code is
located inside of Array parenthesis. The first parameter in array
("my_table" in the example above) should match id of the table. All
other parameters specify type of data in table columns - the second
parameter specifies type of data in the first column, the third
parameter specifies type of data in the second column, and so on.
"Type of data" parameters can be set to:
'i' - Column contains integer data. If the column data contains a number
followed by text then the text will ignored. For example, "54note" will be
interpreted as "54".
'n' - Column contains integer number in which all three-digit
groups are optionally separated from each other by commas. For
example, column data "100,000,000" is treated as "100000000" when type
of data is set to 'n', or as "100" when type of data is set to
'i'.
'f' - Column contains floating point numbers in the form
###.###.
'g' - Column contains floating point numbers in the form ###.###.
Three-digit groups in the floating-point number may be separated from
each other by commas. For example, column data "65,432.1" is treated
as "65432.1" when type of data is set to 'g', or as "65" when type of
data is set to 'f'.
'h' - column contains HTML code. The script will strip all HTML code before sorting the data.
's' - column contains plain text data.
'd' - column contains a date.
'' - do not sort the column.
For example, if you used "sortable_table" id for your table and you
want to sort second column by text, third column by date, forth
column by numbers, and do not sort the first column, then the
javascript code will look like this:
<script type="text/javascript">
<!--
var TSort_Data = new Array ('sortable_table', '', 's', 'd', 'i');
// -->
</script>
If you want to add table sort feature to more than one table on
the page then repeat steps 2, 3 and 4 for each table. Make sure that
javascript code in the step 4 includes "tsRegister();" statement for
each table. If you specify any advanced additional parameters (see
"Advanced Features" section below for more information) then you
don't need to reset them after each call to the tsRegister function
- the function does it automatically.
That's it. The javascript code was tested in IE6, IE7, Firefox 1.5 and 2,
and Opera 9.
Advanced Features
Zebra striping
If you want to use different background colors for odd and even rows
(zebra striping) then you can tell the script to apply background colors
to sorted records. First, create two CSS classes
with background colors for your table. Then add the line below between
<script ...> and </script> tags:
var TSort_Classes = new Array ('class1_name', 'class2_name');
For instance, if you created two classes row1 and row2 for
table rows, and you want to add zebra striping to the example table
from "How to use it" section, then your javascript code will look like this:
<script type="text/javascript">
<!--
var TSort_Data = new Array ('sortable_table', '', 's', 's', 'i');
var TSort_Classes = new Array ('row1', 'row2');
// -->
</script>
You may use the script to do more complex zebra striping.
For example, if you want to use row3 class for every 4th row, and row2
class for all other even rows then TSort_Classes definition will look
like:
var TSort_Classes = new Array ('row1', 'row2', 'row1', 'row3');
Setting initial sorting
You can specify initial sorting order of one or more columns in the
table by setting TSort_Initial variable. To sort one column in
ascending order set this variable to column number:
<script type="text/javascript">
<!--
var TSort_Data = new Array ('sortable_table', '', 's', 's', 'i');
var TSort_Initial = 1;
// -->
</script>
Please note that the column numbering starts from 0, so setting
TSort_Initial to 1 will sort the second column in ascending order.
You can tell the script to set exact sorting order (ascending,
descending or unsorted) for a column if you replace the column number
with a string in format "<column_number><sorting_order>",
where <sorting_order> is:
A - ascending order
D - descending order
U - unsorted
For example, use '1D' string to sort the second column in the descending
order.
To specify initial sorting for multiple columns you'll need to set TSort_Initial
variable to an array containing column numbers and/or column sorting order
strings:
<script type="text/javascript">
<!--
var TSort_Data = new Array ('sortable_table', '', 's', 's', 'i');
var TSort_Initial = new Array (1, '2D');
// -->
</script>
In the example above the table will be sorted by the second column in
ascending order, and then by the third column in descending order.
Using external buttons or objects to change sorting
To change sorting order of any column when a user clicks on a
button, a link, or any other object, add an onClick event to the
object and call a tsDraw function with either a column number or
column sorting order string (see "Setting initial sorting" above) as
the first parameter, and id of the table as the second parameter. The
second parameter can be omitted if you have only one table with
sortable columns, or if you call tsDraw function the second, the
third, etc time in a row for the same table. For example, the button
below will change sorting order of all columns in the table at the top
of this page to "unsorted".
City
Area (km2)
Population (millions)
Mumbai
440
12.78
Karachi
3530
12.21
Below is an HTML code for this button. Notice that only the first
call to tsDraw includes table id:
By default the script uses up and down arrows
to indicate current sorting order. You can replace these two
characters with any other characters, text or HTML code by setting
TSort_Icons variable:
<script type="text/javascript">
<!--
var TSort_Data = new Array ('table_demo_icons', '', 's', 'i', 'f');
var TSort_Icons = new Array (' (Ascending)', ' (Descending)');
// -->
</script>
Here is an example of a table that uses javascript code above:
City
Area (km2)
Population (millions)
Mumbai
440
12.78
Karachi
3530
12.21
TSort_Icons parameter applies only to current table.
If desired, you can replace the characters / text with any HTML
code, including <img ...> tags. Be careful when you do that -
the script changes text color to indicate primary, secondary or
tertiary column, and, if the HTML code contains just an image, then it
will be impossible to differentiate between primary, secondary and
tertiary columns.
Storing sorting order in a cookie
By default, the script does not preserve current sorting order when
the page reloads, or when a visitor leaves the page and returns to it
later. You can tell the script to preserve sorting order for any table
on the page by setting TSort_Cookie variable to cookie name,
preferably the same as table id:
<script type="text/javascript">
<!--
var TSort_Data = new Array ('sortable_table', '', 's', 'i', 'f');
var TSort_Cookie = 'sortable_table';
// -->
</script>
Using the same name for table id and cookie name is not a
requirement, if you wish you give the cookie any name. If you
use gs_sortable script to sort data in multiple tables on the same
page and you want to preserve sorting order for all tables then you
will need to set TSort_Cookie variable for each of those tables. Make
sure that cookie names for all those tables are different!
Changes from version 1.6
The script now handles dates in the following formats:
<year>-<month>-<day> and
<year>-<month>-<day> <hours>:<minutes>:<seconds>.
Version 1.7 of the script is backwards compatible with older versions
of the script. Replacing old versions of the script with the version 1.6
doesn't require any changes to HTML pages.
Changes from version 1.5
The script now properly handles tables that have two header rows.
For an example please see the first demo table on this page.
Version 1.6 of the script is backwards compatible with older versions
of the script. Replacing old versions of the script with the version 1.6
doesn't require any changes to HTML pages.
Changes from version 1.4
The script can now sort integer and floating-point data where three-digit
groups are separated by commas ('n' and 'g' data type parameters).
Version 1.5 of the script is compatible with older versions of the
script. You can replace old version of the script with the version 1.5
without changing your HTML pages.
Changes from version 1.3
The script now supports multiple tables.
Added sorting by date.
Sorting order can be optionally stored in a cookie, and restored
when a visitor returns to the page later.
Up/Down arrows can be optionally changed to different character
or image.
Version 1.4 of the script is compatible with older versions of the
script. You can replace old version of the script with the version 1.4
without changing your HTML pages.
Changes from version 1.2
You can specify exact sorting order for one or more columns.
Added "HTML code" data type.
Fixed a bug where a script wouldn't start at all.
Version 1.3 of the script is compatible with older versions of the
script. You can replace old version of the script with the version 1.3
without changing your HTML pages.
Changes from version 1.1
You can specify initial sorting order of the columns in the version
1.2.
Version 1.2 of the script is directly compatible with versions 1.1
and 1.0. You can replace old version of the script with the new
version without changing your HTML pages. You will need to make a
small change in HTML pages if you want to add support for setting
initial sorting order.
Changes from version 1.0
You can switch columns back to unsorted order. The first click
on any unsorted column header sorts the data in ascending order, the
second click makes it sort in descending order, and the third click
now switches the column to unsorted order.
You can tell the script to apply zebra striping to sorted
records.
Identical data in sorted columns is now displayed in the same
order as it was supplied in the HTML document.
Version 1.1 of the script is directly compatible with version 1.0.
You can replace old version of the script with the new version without
changing your HTML pages. You will need to make a small change in HTML
pages if you want to add support for table zebra striping.
The script is released under GPL v3.0 license. You're welcome to
distribute the script and to use it on your web pages if you like. If you decide to modify it
please make sure that you release the changed code.
Contact
If you have any questions, corrections or additions to the code,
you can contact me using this form.
Spread the word:
If you use this script and like it please consider adding a link to this
page. This will make it easier for other people to find this
script. And the more people use the script the more I'll be inclined to
improve it.