5
Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
9
Add <script src="sorttable.js"></script> to your HTML
10
Add class="sortable" to any table you'd like to make sortable
11
Click on the headers to sort
13
Thanks to many, many people for contributions and suggestions.
14
Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
15
This basically means: do what you want with it.
19
var stIsIE = /*@cc_on!@*/false;
23
// quit if this function has already been called
24
if (arguments.callee.done) return;
25
// flag this function so we don't do the same thing twice
26
arguments.callee.done = true;
28
if (_timer) clearInterval(_timer);
30
if (!document.createElement || !document.getElementsByTagName) return;
32
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
34
forEach(document.getElementsByTagName('table'), function(table) {
35
if (table.className.search(/\bsortable\b/) != -1) {
36
sorttable.makeSortable(table);
42
makeSortable: function(table) {
43
if (table.getElementsByTagName('thead').length == 0) {
44
if(table.rows.length == 0)
46
// table doesn't have a tHead. Since it should have, create one and
47
// put the first table row in it.
48
the = document.createElement('thead');
49
the.appendChild(table.rows[0]);
50
table.insertBefore(the,table.firstChild);
52
// Safari doesn't support table.tHead, sigh
53
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
55
if (table.tHead.rows.length != 1) return; // can't cope with two header rows
57
// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
58
// "total" rows, for example). This is B&R, since what you're supposed
59
// to do is put them in a tfoot. So, if there are sortbottom rows,
60
// for backwards compatibility, move them to tfoot (creating it if needed).
62
for (var i=0; i<table.rows.length; i++) {
63
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
64
sortbottomrows[sortbottomrows.length] = table.rows[i];
68
if (table.tFoot == null) {
69
// table doesn't have a tfoot. Create one.
70
tfo = document.createElement('tfoot');
71
table.appendChild(tfo);
73
for (var i=0; i<sortbottomrows.length; i++) {
74
tfo.appendChild(sortbottomrows[i]);
76
delete sortbottomrows;
79
// work through each column and calculate its type
80
headrow = table.tHead.rows[0].cells;
81
for (var i=0; i<headrow.length; i++) {
82
// manually override the type with a sorttable_type attribute
83
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
84
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
85
if (mtch) { override = mtch[1]; }
86
if (mtch && typeof sorttable["sort_"+override] == 'function') {
87
headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
89
headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
91
// make it clickable to sort
92
headrow[i].sorttable_columnindex = i;
93
headrow[i].sorttable_tbody = table.tBodies[0];
94
dean_addEvent(headrow[i],"click", function(e) {
96
if (this.className.search(/\bsorttable_sorted\b/) != -1) {
97
// if we're already sorted by this column, just
98
// reverse the table, which is quicker
99
sorttable.reverse(this.sorttable_tbody);
100
this.className = this.className.replace('sorttable_sorted',
101
'sorttable_sorted_reverse');
102
this.removeChild(document.getElementById('sorttable_sortfwdind'));
103
sortrevind = document.createElement('span');
104
sortrevind.id = "sorttable_sortrevind";
105
sortrevind.innerHTML = stIsIE ? ' <font face="webdings">5</font>' : ' ▴';
106
this.appendChild(sortrevind);
109
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
110
// if we're already sorted by this column in reverse, just
111
// re-reverse the table, which is quicker
112
sorttable.reverse(this.sorttable_tbody);
113
this.className = this.className.replace('sorttable_sorted_reverse',
115
this.removeChild(document.getElementById('sorttable_sortrevind'));
116
sortfwdind = document.createElement('span');
117
sortfwdind.id = "sorttable_sortfwdind";
118
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
119
this.appendChild(sortfwdind);
123
// remove sorttable_sorted classes
124
theadrow = this.parentNode;
125
forEach(theadrow.childNodes, function(cell) {
126
if (cell.nodeType == 1) { // an element
127
cell.className = cell.className.replace('sorttable_sorted_reverse','');
128
cell.className = cell.className.replace('sorttable_sorted','');
131
sortfwdind = document.getElementById('sorttable_sortfwdind');
132
if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
133
sortrevind = document.getElementById('sorttable_sortrevind');
134
if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
136
this.className += ' sorttable_sorted';
137
sortfwdind = document.createElement('span');
138
sortfwdind.id = "sorttable_sortfwdind";
139
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
140
this.appendChild(sortfwdind);
142
// build an array to sort. This is a Schwartzian transform thing,
143
// i.e., we "decorate" each row with the actual sort key,
144
// sort based on the sort keys, and then put the rows back in order
145
// which is a lot faster because you only do getInnerText once per row
147
col = this.sorttable_columnindex;
148
rows = this.sorttable_tbody.rows;
149
for (var j=0; j<rows.length; j++) {
150
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
152
/* If you want a stable sort, uncomment the following line */
153
//sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
154
/* and comment out this one */
155
row_array.sort(this.sorttable_sortfunction);
157
tb = this.sorttable_tbody;
158
for (var j=0; j<row_array.length; j++) {
159
tb.appendChild(row_array[j][1]);
168
guessType: function(table, column) {
169
// guess the type of a column based on its first non-blank row
170
sortfn = sorttable.sort_alpha;
171
for (var i=0; i<table.tBodies[0].rows.length; i++) {
172
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
174
if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
175
return sorttable.sort_numeric;
177
// check for a date: dd/mm/yyyy or dd/mm/yy
178
// can have / or . or - as separator
179
// can be mm/dd as well
180
possdate = text.match(sorttable.DATE_RE)
183
first = parseInt(possdate[1]);
184
second = parseInt(possdate[2]);
187
return sorttable.sort_ddmm;
188
} else if (second > 12) {
189
return sorttable.sort_mmdd;
191
// looks like a date, but we can't tell which, so assume
192
// that it's dd/mm (English imperialism!) and keep looking
193
sortfn = sorttable.sort_ddmm;
201
getInnerText: function(node) {
202
// gets the text we want to use for sorting for a cell.
203
// strips leading and trailing whitespace.
204
// this is *not* a generic getInnerText function; it's special to sorttable.
205
// for example, you can override the cell text with a customkey attribute.
206
// it also gets .value for <input> fields.
208
hasInputs = (typeof node.getElementsByTagName == 'function') &&
209
node.getElementsByTagName('input').length;
211
if (node.getAttribute("sorttable_customkey") != null) {
212
return node.getAttribute("sorttable_customkey");
214
else if (typeof node.textContent != 'undefined' && !hasInputs) {
215
return node.textContent.replace(/^\s+|\s+$/g, '');
217
else if (typeof node.innerText != 'undefined' && !hasInputs) {
218
return node.innerText.replace(/^\s+|\s+$/g, '');
220
else if (typeof node.text != 'undefined' && !hasInputs) {
221
return node.text.replace(/^\s+|\s+$/g, '');
224
switch (node.nodeType) {
226
if (node.nodeName.toLowerCase() == 'input') {
227
return node.value.replace(/^\s+|\s+$/g, '');
230
return node.nodeValue.replace(/^\s+|\s+$/g, '');
235
for (var i = 0; i < node.childNodes.length; i++) {
236
innerText += sorttable.getInnerText(node.childNodes[i]);
238
return innerText.replace(/^\s+|\s+$/g, '');
246
reverse: function(tbody) {
247
// reverse the rows in a tbody
249
for (var i=0; i<tbody.rows.length; i++) {
250
newrows[newrows.length] = tbody.rows[i];
252
for (var i=newrows.length-1; i>=0; i--) {
253
tbody.appendChild(newrows[i]);
259
each sort function takes two parameters, a and b
260
you are comparing a[0] and b[0] */
261
sort_numeric: function(a,b) {
262
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
263
if (isNaN(aa)) aa = 0;
264
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
265
if (isNaN(bb)) bb = 0;
268
sort_alpha: function(a,b) {
269
if (a[0]==b[0]) return 0;
270
if (a[0]<b[0]) return -1;
273
sort_ddmm: function(a,b) {
274
mtch = a[0].match(sorttable.DATE_RE);
275
y = mtch[3]; m = mtch[2]; d = mtch[1];
276
if (m.length == 1) m = '0'+m;
277
if (d.length == 1) d = '0'+d;
279
mtch = b[0].match(sorttable.DATE_RE);
280
y = mtch[3]; m = mtch[2]; d = mtch[1];
281
if (m.length == 1) m = '0'+m;
282
if (d.length == 1) d = '0'+d;
284
if (dt1==dt2) return 0;
285
if (dt1<dt2) return -1;
288
sort_mmdd: function(a,b) {
289
mtch = a[0].match(sorttable.DATE_RE);
290
y = mtch[3]; d = mtch[2]; m = mtch[1];
291
if (m.length == 1) m = '0'+m;
292
if (d.length == 1) d = '0'+d;
294
mtch = b[0].match(sorttable.DATE_RE);
295
y = mtch[3]; d = mtch[2]; m = mtch[1];
296
if (m.length == 1) m = '0'+m;
297
if (d.length == 1) d = '0'+d;
299
if (dt1==dt2) return 0;
300
if (dt1<dt2) return -1;
304
shaker_sort: function(list, comp_func) {
305
// A stable sort function to allow multi-level sorting of data
306
// see: http://en.wikipedia.org/wiki/Cocktail_sort
307
// thanks to Joseph Nahmias
309
var t = list.length - 1;
314
for(var i = b; i < t; ++i) {
315
if ( comp_func(list[i], list[i+1]) > 0 ) {
316
var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
324
for(var i = t; i > b; --i) {
325
if ( comp_func(list[i], list[i-1]) < 0 ) {
326
var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
336
/* ******************************************************************
337
Supporting functions: bundled here to avoid depending on a library
338
****************************************************************** */
340
// Dean Edwards/Matthias Miller/John Resig
342
/* for Mozilla/Opera9 */
343
if (document.addEventListener) {
344
document.addEventListener("DOMContentLoaded", sorttable.init, false);
347
/* for Internet Explorer */
350
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
351
var script = document.getElementById("__ie_onload");
352
script.onreadystatechange = function() {
353
if (this.readyState == "complete") {
354
sorttable.init(); // call the onload handler
360
if (/WebKit/i.test(navigator.userAgent)) { // sniff
361
var _timer = setInterval(function() {
362
if (/loaded|complete/.test(document.readyState)) {
363
sorttable.init(); // call the onload handler
368
/* for other browsers */
369
window.onload = sorttable.init;
371
// written by Dean Edwards, 2005
372
// with input from Tino Zijdel, Matthias Miller, Diego Perini
374
// http://dean.edwards.name/weblog/2005/10/add-event/
376
function dean_addEvent(element, type, handler) {
377
if (element.addEventListener) {
378
element.addEventListener(type, handler, false);
380
// assign each event handler a unique ID
381
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
382
// create a hash table of event types for the element
383
if (!element.events) element.events = {};
384
// create a hash table of event handlers for each element/event pair
385
var handlers = element.events[type];
387
handlers = element.events[type] = {};
388
// store the existing event handler (if there is one)
389
if (element["on" + type]) {
390
handlers[0] = element["on" + type];
393
// store the event handler in the hash table
394
handlers[handler.$$guid] = handler;
395
// assign a global event handler to do all the work
396
element["on" + type] = handleEvent;
399
// a counter used to create unique IDs
400
dean_addEvent.guid = 1;
402
function removeEvent(element, type, handler) {
403
if (element.removeEventListener) {
404
element.removeEventListener(type, handler, false);
406
// delete the event handler from the hash table
407
if (element.events && element.events[type]) {
408
delete element.events[type][handler.$$guid];
413
function handleEvent(event) {
414
var returnValue = true;
415
// grab the event object (IE uses a global event object)
416
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
417
// get a reference to the hash table of event handlers
418
var handlers = this.events[event.type];
419
// execute each event handler
420
for (var i in handlers) {
421
this.$$handleEvent = handlers[i];
422
if (this.$$handleEvent(event) === false) {
429
function fixEvent(event) {
430
// add W3C standard event methods
431
event.preventDefault = fixEvent.preventDefault;
432
event.stopPropagation = fixEvent.stopPropagation;
435
fixEvent.preventDefault = function() {
436
this.returnValue = false;
438
fixEvent.stopPropagation = function() {
439
this.cancelBubble = true;
442
// Dean's forEach: http://dean.edwards.name/base/forEach.js
445
Copyright 2006, Dean Edwards
446
License: http://www.opensource.org/licenses/mit-license.php
449
// array-like enumeration
450
if (!Array.forEach) { // mozilla already supports this
451
Array.forEach = function(array, block, context) {
452
for (var i = 0; i < array.length; i++) {
453
block.call(context, array[i], i, array);
458
// generic enumeration
459
Function.prototype.forEach = function(object, block, context) {
460
for (var key in object) {
461
if (typeof this.prototype[key] == "undefined") {
462
block.call(context, object[key], key, object);
467
// character enumeration
468
String.forEach = function(string, block, context) {
469
Array.forEach(string.split(""), function(chr, index) {
470
block.call(context, chr, index, string);
474
// globally resolve forEach enumeration
475
var forEach = function(object, block, context) {
477
var resolve = Object; // default
478
if (object instanceof Function) {
479
// functions have a "length" property
481
} else if (object.forEach instanceof Function) {
482
// the object implements a custom forEach method so use that
483
object.forEach(block, context);
485
} else if (typeof object == "string") {
486
// the object is a string
488
} else if (typeof object.length == "number") {
489
// the object is array-like
492
resolve.forEach(object, block, context);