Tony's Friendly Table Sorter
This is – I think – my first cup of awesomesauce, ever. This code is beautiful. I've had a lot of Open Source projects, yes. But they were all done fast – in a weekend, when I could cram it in. But this baby? She's all curves. Try clicking these table headers:
|Geeema||1.0.1||goop#5||$5||27 Feb 2008|
|Hello World!||1.0||tisad||$5,000||21 Apr 2008|
|when?||1.0.3||illinois||$5000.01||20 Feb 2008|
|en-us||1.0.1||#du||$500.00||10 Apr 2008|
Yeah. Want a cup? It's yours, for free.
The script that I latched onto was created by Joost de Valk. His script is based upon another script, created by Stuart Langridge. Because Stuart put his script out under an MIT license, Joost could expand Stuart's work, and I am able to expand Joost's work. Thanks to Stuart for having the foresight to use the MIT license.
This script contains all of the features of Joost's version (alternating colors for table rows, smart sorting based upon what it thinks the data is) along with the following improvements:
- Doesn't accidentally use the table header to try to determine the sort type.
- Space is allowed as separator between date fields.
- Created a "sort type override" feature.
- Replaced broken arrow images with arrow glyph from standard font.
- Refactored into a namespace so that there are no name collisions.
- Better handling of US vs. non-US number formats.
- Better handling of currency.
- Faster trim function (imperceptible).
- Cleaner sorting code (not faster, just neater).
- Consistent naming convention for functions/methods.
- Very clear comments to walk you through the code.
The new "Sort type override" feature
The sorting system can (rarely) make an incorrect guess as to how to sort a column. For example, version numbers are usually sorted as numbers. However, they are not actually numbers. They have multiple decimal points, which is not possible in a real number. Thus, you can see the sorting go wrong sometimes, and you need to override it. To do this, see the "how-to" section below.
To get it working, download the minimized version, save it as a .js file (not .txt) onto your server, and then include this line in your HTML header:
You're not quite done. You also need to flag each table that you'd like to be sorted. You do this by adding the class "sortable" to the table(s). Like this:
That's typically enough to get things working. But there is an optional step. If you need to override the way it sorts a particular column, you can add a class to your table header (the TH tag). It can be sortAlpha, sortNumeric, or sortDate. Like this:
My script is under an MIT license, just like Stuart's & Joost's scripts. If you extend my script and release your version, you cannot remove the copyright, nor can you remove our names from the script. But you CAN use this script for your own personal site or even for a company. Just keep the copyright & link to the license intact.