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:
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.
| City Name | City Information | |
|---|---|---|
| Area (km2) | Population (millions) | |
| Mumbai | 440 | 12.78 |
| Karachi | 3530 | 12.21 |
| Delhi | 1400 | 11.06 |
| San Paulo | 1520 | 10.84 |
| Moscow | 1081 | 10.38 |
| US City | State | Population (millions) |
|---|---|---|
| New York | New York | 8,274,527 |
| Los Angeles | California | 3,834,340 |
| Chicago | Illinois | 2,836,658 |
| Houston | Texas | 2,208,180 |
| Phoenix | Arizona | 1,552,259 |
It is important to note that all data types, except 's' and '', strip all HTML code from data columns before sorting.
As an example of sortable table with different data types, let's pretend that you want to show recent sales of some equipment, and include equipment name, sale date, sale price and the number of units sold. If you want to sort all columns in this table, then the data type for the first column will be 's' (string) or 'h' (HTML code), the second column will have 'd' (date) data type, the third column will have 'c' (currency) data type, and the last column should be set to data type 'i' (integer) or 'n' (a number). Assuming that the table has "sortable_table" id, the javascript code will look like this:
Below is an example of the table, that uses javascript code above:
| Product | Date | Price per unit | Units sold |
|---|---|---|---|
| Item A | 13/5/2012 | $25.15 | 20 |
| Item B | 14/5/2012 | $35 | 1 |
| Item A | 14/5/2012 | $28 | 1 |
| Item C | 15/5/2012 | $20 | 100 |
That's it. The javascript code was tested in the latest versions of IE6, Firefox, Chrome and Opera browsers.
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:
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:
If you set initial sorting (please see "Setting initial sorting" feature for more details), you can force the gs_sortable to apply zebra classes when the web page is loaded. For instance, to sort the first column in ascending order you will need this code:
By default, when Zebra striping is enabled, the script sets classes for TR tags from the TSort_Classes array, wiping out whatever classes the TR tags had beforehand. You can tell the script to append Zebra classes instead by setting TSort_AppendClasses variable:
Be warned that Zebra striping may not work correctly if the table is generated with Zebra striping classes by your server script, and the TSort_AppendClasses variable is set.
To demonstrate all possible Zebra striping options, let's assume that you want to have even/odd zebra striping, you want to preserve highlighting of one or more rows in the table, and that the table's first column by default is sorted in ascending order. In this case your javascript code will look like this:
Here is a sample table that uses similar javascript initialization code:
| US City | State | Population (millions) |
|---|---|---|
| Chicago | Illinois | 2,836,658 |
| Houston | Texas | 2,208,180 |
| Los Angeles | California | 3,834,340 |
| New York | New York | 8,274,527 |
| Phoenix | Arizona | 1,552,259 |
As you can see, the script automatically applies the row1/row2 classes to the table when the page is loaded, as well as when the data is sorted, while preserving highlighting of the row with numbers for New York city.
The gs_sortable script may be used 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:
The gs_sortable script was originally designed to handle simple HTML tables, that have one set of data per each row. Starting from version 1.9, the gs_sortable script may work with complex tables, that utilize multiple rows to display one set of data. For example, the table may show population of US states, using 4 separate table rows for each state: the first row is for the state population, and the following three rows are for the three largest cities. One of the possible ways to sort data in such table is to sort only rows with state population, and ignore all other rows with city data. At the same time, the script should be smart enough to keep city data next to the row with the state data, when the state row is moved around. This type of sorting can be accomplished by adding hints to table rows. Specifically, all rows, that shouldn't be sorted, must have "_nosort" CSS class name set:
All TR rows without "_nosort" class are treated as sortable, and the rows with the "_nosort" class are handled as child rows, attached to their parent row. In the example above, the row with New York state data is a parent row, that will be sorted by the gs_sortable. Three other rows with city data are moved along with the parent row when the position of the parent row changes in the table. Below is an example of complex table, containing only three states:
| State / City | Population |
|---|---|
| New Mexico | 2,082,224 |
| Albuquerque | 545,852 |
| Las Cruces | 97,618 |
| Rio Rancho | 87,521 |
| New York state | 19,465,197 |
| New York City | 8,175,133 |
| Buffalo | 261,310 |
| Rochester | 210,565 |
| North Carolina | 9,656,401 |
| Charlotte | 731,424 |
| Raleigh | 403,892 |
| Greensboro | 269,666 |
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:
The button below will sort in ascending order three columns in the table:
HTML code for the button:
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:
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.
By default, the script sorts data in the primary column (that was sorted the last). All data values, that are identical in that column, are sorted based on the secondary column, and if they are still identical then gs_sortable uses data from the tertiary column. Sometimes it is needed to sort data in more than three columns at once, at other times you may need to sort data only in one or two columns. You can easily adjust the number of sortable columns by setting TSort_NColumns variable:
Here is a sample table that uses javascript code above:
| City | Area (km2) | Population (millions) |
|---|---|---|
| Mumbai | 440 | 12.78 |
| Karachi | 3530 | 12.21 |
When a web page is loaded, the gs_sortable script automatically registers and initializes all sortable tables on the page. During initialization phase, the script parses table contents, and saves parsed values so that they can be used at a later time without re-parsing. It also makes copies of table rows. The problems arise when the page contains dynamically loaded tables, i.e. tables, which contents is modified by javascript code after the page finished loading. The gs_sortable script does not know that the contents of the table was dynamically changed, and it happily uses previously stored data to sort columns' data. As a result, it may replace the contents of updated table with the original contents, that existed when the page was loaded.
Nevertheless, dynamic tables do work with the gs_sortable if they are properly registered and initialized immediately after they were modified. Below is an example of initialization code for dynamic table with id "table_demo_dyn1":
You may need to define TSort_Data variable if it's not defined elsewhere on the page. It is recommended to implement initialization code as a function, so you can call it when needed. Below is an example of two dynamically loaded tables, that use initialization function, similar to the provided one. This example uses hardcoded table contents, although the same approach can be used with table data, loaded by AJAX script:
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:
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!
Some of the changes and fixes were submitted by Vilem Marsik and Andrey Elistratov. Thank you!
Version 1.9 of the script is backwards compatible with older versions of the script. Replacing old versions of the script with the version 1.9 should not require any changes to HTML pages.
The script can handle US currency in the form $XXX.XX.
Tables without rows no longer result in javascript error. This change incorporates fix supplied by David Sacker.
Version 1.8 of the script is backwards compatible with older versions of the script. Replacing old versions of the script with the version 1.8 doesn't require any changes to HTML pages.
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.7 doesn't require any changes to HTML pages.
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.
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.
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.
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.
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.
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.
gs_sortable.js v1.9 (beta version) - uncompressed file
gs_sortable.js v1.8 (latest stable version) - uncompressed file
gs_sortable.js v1.7 - uncompressed file
gs_sortable.js v1.6 - uncompressed file
gs_sortable.js v1.5 - uncompressed file
gs_sortable.js v1.4 - uncompressed file
gs_sortable.js v1.3 - uncompressed file
gs_sortable.js v1.2 - uncompressed file
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.
If you have any questions, corrections or additions to the code, you can contact me using this form.
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.
| (c) Copyright 2007 - 2009 Gennadiy Shvets |