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.
20 -Specify which coloumns to sort or not by changing index in makeSortable().
21 -To avoid including the non-data rows (e.g., radio buttions) into sorting,
22 add index and row handling (deletion and appending) in makeSortable() and
24 -Remove the init parts for other browsers.
27 var stIsIE = /*@cc_on!@*/false;
31 // quit if this function has already been called
32 if (arguments.callee.done) return;
33 // flag this function so we don't do the same thing twice
34 arguments.callee.done = true;
36 if (!document.createElement || !document.getElementsByTagName) return;
38 sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
40 forEach(document.getElementsByTagName('table'), function(table) {
41 if (table.className.search(/\bsortable\b/) != -1) {
42 sorttable.makeSortable(table);
48 makeSortable: function(table) {
49 if (table.getElementsByTagName('thead').length == 0) {
50 // table doesn't have a tHead. Since it should have, create one and
51 // put the first table row in it.
52 the = document.createElement('thead');
53 the.appendChild(table.rows[0]);
54 table.insertBefore(the,table.firstChild);
56 // Safari doesn't support table.tHead, sigh
57 if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
59 if (table.tHead.rows.length != 1) return; // can't cope with two header rows
61 // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
62 // "total" rows, for example). This is B&R, since what you're supposed
63 // to do is put them in a tfoot. So, if there are sortbottom rows,
64 // for backwards compatibility, move them to tfoot (creating it if needed).
66 for (var i=0; i<table.rows.length; i++) {
67 if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
68 sortbottomrows[sortbottomrows.length] = table.rows[i];
72 if (table.tFoot == null) {
73 // table doesn't have a tfoot. Create one.
74 tfo = document.createElement('tfoot');
75 table.appendChild(tfo);
77 for (var i=0; i<sortbottomrows.length; i++) {
78 tfo.appendChild(sortbottomrows[i]);
80 delete sortbottomrows;
83 // work through each column and calculate its type
84 headrow = table.tHead.rows[0].cells;
85 for (var i=5; i<headrow.length-1; i++) {
86 // manually override the type with a sorttable_type attribute
87 if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
88 mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
89 if (mtch) { override = mtch[1]; }
90 if (mtch && typeof sorttable["sort_"+override] == 'function') {
91 headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
93 headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
95 // make it clickable to sort
96 headrow[i].sorttable_columnindex = i;
97 headrow[i].sorttable_tbody = table.tBodies[0];
98 dean_addEvent(headrow[i],"click", function(e) {
100 if (this.className.search(/\bsorttable_sorted\b/) != -1) {
101 // if we're already sorted by this column, just
102 // reverse the table, which is quicker
103 sorttable.reverse(this.sorttable_tbody);
104 this.className = this.className.replace('sorttable_sorted',
105 'sorttable_sorted_reverse');
106 this.removeChild(document.getElementById('sorttable_sortfwdind'));
107 sortrevind = document.createElement('span');
108 sortrevind.id = "sorttable_sortrevind";
109 sortrevind.innerHTML = stIsIE ? ' <font face="webdings">5</font>' : ' ▴';
110 this.appendChild(sortrevind);
113 if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
114 // if we're already sorted by this column in reverse, just
115 // re-reverse the table, which is quicker
116 sorttable.reverse(this.sorttable_tbody);
117 this.className = this.className.replace('sorttable_sorted_reverse',
119 this.removeChild(document.getElementById('sorttable_sortrevind'));
120 sortfwdind = document.createElement('span');
121 sortfwdind.id = "sorttable_sortfwdind";
122 sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
123 this.appendChild(sortfwdind);
127 // remove sorttable_sorted classes
128 theadrow = this.parentNode;
129 forEach(theadrow.childNodes, function(cell) {
130 if (cell.nodeType == 1) { // an element
131 cell.className = cell.className.replace('sorttable_sorted_reverse','');
132 cell.className = cell.className.replace('sorttable_sorted','');
135 sortfwdind = document.getElementById('sorttable_sortfwdind');
136 if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
137 sortrevind = document.getElementById('sorttable_sortrevind');
138 if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
140 this.className += ' sorttable_sorted';
141 sortfwdind = document.createElement('span');
142 sortfwdind.id = "sorttable_sortfwdind";
143 sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
144 this.appendChild(sortfwdind);
146 // build an array to sort. This is a Schwartzian transform thing,
147 // i.e., we "decorate" each row with the actual sort key,
148 // sort based on the sort keys, and then put the rows back in order
149 // which is a lot faster because you only do getInnerText once per row
151 col = this.sorttable_columnindex;
152 rows = this.sorttable_tbody.rows;
153 for (var j=1; j<rows.length-3; j++) {
154 row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
156 /* If you want a stable sort, uncomment the following line */
157 sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
158 /* and comment out this one */
159 //row_array.sort(this.sorttable_sortfunction);
161 tb = this.sorttable_tbody;
162 var noTestRow = tb.rows[tb.rows.length-3];
163 var radioRow = tb.rows[tb.rows.length-2];
164 var compareRow = tb.rows[tb.rows.length-1];
165 tb.deleteRow(tb.rows.length-1);
166 tb.deleteRow(tb.rows.length-1);
167 tb.deleteRow(tb.rows.length-1);
168 for (var j=0; j<row_array.length; j++) {
169 tb.appendChild(row_array[j][1]);
171 tb.appendChild(noTestRow);
172 tb.appendChild(radioRow);
173 tb.appendChild(compareRow);
183 guessType: function(table, column) {
184 // guess the type of a column based on its first non-blank row
185 sortfn = sorttable.sort_numeric;
186 for (var i=0; i<table.tBodies[0].rows.length-3; i++) {
187 text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
189 if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
190 return sorttable.sort_numeric;
192 // check for a date: dd/mm/yyyy or dd/mm/yy
193 // can have / or . or - as separator
194 // can be mm/dd as well
195 possdate = text.match(sorttable.DATE_RE)
198 first = parseInt(possdate[1]);
199 second = parseInt(possdate[2]);
202 return sorttable.sort_ddmm;
203 } else if (second > 12) {
204 return sorttable.sort_mmdd;
206 // looks like a date, but we can't tell which, so assume
207 // that it's dd/mm (English imperialism!) and keep looking
208 sortfn = sorttable.sort_ddmm;
216 getInnerText: function(node) {
217 // gets the text we want to use for sorting for a cell.
218 // strips leading and trailing whitespace.
219 // this is *not* a generic getInnerText function; it's special to sorttable.
220 // for example, you can override the cell text with a customkey attribute.
221 // it also gets .value for <input> fields.
223 hasInputs = (typeof node.getElementsByTagName == 'function') &&
224 node.getElementsByTagName('input').length;
226 if (node.getAttribute("sorttable_customkey") != null) {
227 return node.getAttribute("sorttable_customkey");
229 else if (typeof node.textContent != 'undefined' && !hasInputs) {
230 return node.textContent.replace(/^\s+|\s+$/g, '');
232 else if (typeof node.innerText != 'undefined' && !hasInputs) {
233 return node.innerText.replace(/^\s+|\s+$/g, '');
235 else if (typeof node.text != 'undefined' && !hasInputs) {
236 return node.text.replace(/^\s+|\s+$/g, '');
239 switch (node.nodeType) {
241 if (node.nodeName.toLowerCase() == 'input') {
242 return node.value.replace(/^\s+|\s+$/g, '');
245 return node.nodeValue.replace(/^\s+|\s+$/g, '');
250 for (var i = 0; i < node.childNodes.length; i++) {
251 innerText += sorttable.getInnerText(node.childNodes[i]);
253 return innerText.replace(/^\s+|\s+$/g, '');
261 reverse: function(tbody) {
262 // reverse the rows in a tbody
264 for (var i=0; i<tbody.rows.length; i++) {
265 newrows[newrows.length] = tbody.rows[i];
267 tbody.appendChild(newrows[0]);
268 for (var i=newrows.length-4; i>0; i--) {
269 tbody.appendChild(newrows[i]);
271 tbody.appendChild(newrows[newrows.length-3]);
272 tbody.appendChild(newrows[newrows.length-2]);
273 tbody.appendChild(newrows[newrows.length-1]);
278 each sort function takes two parameters, a and b
279 you are comparing a[0] and b[0] */
280 sort_numeric: function(a,b) {
281 aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
282 if (isNaN(aa)) aa = 0;
283 bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
284 if (isNaN(bb)) bb = 0;
287 sort_alpha: function(a,b) {
288 if (a[0]==b[0]) return 0;
289 if (a[0]<b[0]) return -1;
292 sort_ddmm: function(a,b) {
293 mtch = a[0].match(sorttable.DATE_RE);
294 y = mtch[3]; m = mtch[2]; d = mtch[1];
295 if (m.length == 1) m = '0'+m;
296 if (d.length == 1) d = '0'+d;
298 mtch = b[0].match(sorttable.DATE_RE);
299 y = mtch[3]; m = mtch[2]; d = mtch[1];
300 if (m.length == 1) m = '0'+m;
301 if (d.length == 1) d = '0'+d;
303 if (dt1==dt2) return 0;
304 if (dt1<dt2) return -1;
307 sort_mmdd: function(a,b) {
308 mtch = a[0].match(sorttable.DATE_RE);
309 y = mtch[3]; d = mtch[2]; m = mtch[1];
310 if (m.length == 1) m = '0'+m;
311 if (d.length == 1) d = '0'+d;
313 mtch = b[0].match(sorttable.DATE_RE);
314 y = mtch[3]; d = mtch[2]; m = mtch[1];
315 if (m.length == 1) m = '0'+m;
316 if (d.length == 1) d = '0'+d;
318 if (dt1==dt2) return 0;
319 if (dt1<dt2) return -1;
323 shaker_sort: function(list, comp_func) {
324 // A stable sort function to allow multi-level sorting of data
325 // see: http://en.wikipedia.org/wiki/Cocktail_sort
326 // thanks to Joseph Nahmias
328 var t = list.length - 1;
333 for(var i = b; i < t; ++i) {
334 if ( comp_func(list[i], list[i+1]) > 0 ) {
335 var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
343 for(var i = t; i > b; --i) {
344 if ( comp_func(list[i], list[i-1]) < 0 ) {
345 var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
355 /* ******************************************************************
356 Supporting functions: bundled here to avoid depending on a library
357 ****************************************************************** */
359 // Dean Edwards/Matthias Miller/John Resig
361 /* for other browsers */
362 window.onload = sorttable.init;
364 // written by Dean Edwards, 2005
365 // with input from Tino Zijdel, Matthias Miller, Diego Perini
367 // http://dean.edwards.name/weblog/2005/10/add-event/
369 function dean_addEvent(element, type, handler) {
370 if (element.addEventListener) {
371 element.addEventListener(type, handler, false);
373 // assign each event handler a unique ID
374 if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
375 // create a hash table of event types for the element
376 if (!element.events) element.events = {};
377 // create a hash table of event handlers for each element/event pair
378 var handlers = element.events[type];
380 handlers = element.events[type] = {};
381 // store the existing event handler (if there is one)
382 if (element["on" + type]) {
383 handlers[0] = element["on" + type];
386 // store the event handler in the hash table
387 handlers[handler.$$guid] = handler;
388 // assign a global event handler to do all the work
389 element["on" + type] = handleEvent;
392 // a counter used to create unique IDs
393 dean_addEvent.guid = 1;
395 function removeEvent(element, type, handler) {
396 if (element.removeEventListener) {
397 element.removeEventListener(type, handler, false);
399 // delete the event handler from the hash table
400 if (element.events && element.events[type]) {
401 delete element.events[type][handler.$$guid];
406 function handleEvent(event) {
407 var returnValue = true;
408 // grab the event object (IE uses a global event object)
409 event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
410 // get a reference to the hash table of event handlers
411 var handlers = this.events[event.type];
412 // execute each event handler
413 for (var i in handlers) {
414 this.$$handleEvent = handlers[i];
415 if (this.$$handleEvent(event) === false) {
422 function fixEvent(event) {
423 // add W3C standard event methods
424 event.preventDefault = fixEvent.preventDefault;
425 event.stopPropagation = fixEvent.stopPropagation;
428 fixEvent.preventDefault = function() {
429 this.returnValue = false;
431 fixEvent.stopPropagation = function() {
432 this.cancelBubble = true;
435 // Dean's forEach: http://dean.edwards.name/base/forEach.js
438 Copyright 2006, Dean Edwards
439 License: http://www.opensource.org/licenses/mit-license.php
442 // array-like enumeration
443 if (!Array.forEach) { // mozilla already supports this
444 Array.forEach = function(array, block, context) {
445 for (var i = 0; i < array.length; i++) {
446 block.call(context, array[i], i, array);
451 // generic enumeration
452 Function.prototype.forEach = function(object, block, context) {
453 for (var key in object) {
454 if (typeof this.prototype[key] == "undefined") {
455 block.call(context, object[key], key, object);
460 // character enumeration
461 String.forEach = function(string, block, context) {
462 Array.forEach(string.split(""), function(chr, index) {
463 block.call(context, chr, index, string);
467 // globally resolve forEach enumeration
468 var forEach = function(object, block, context) {
470 var resolve = Object; // default
471 if (object instanceof Function) {
472 // functions have a "length" property
474 } else if (object.forEach instanceof Function) {
475 // the object implements a custom forEach method so use that
476 object.forEach(block, context);
478 } else if (typeof object == "string") {
479 // the object is a string
481 } else if (typeof object.length == "number") {
482 // the object is array-like
485 resolve.forEach(object, block, context);