535 lines · javascript
1/*2 SortTable3 version 24 7th April 20075 Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/6 7 Instructions:8 Download this file9 Add <script src="sorttable.js"></script> to your HTML10 Add class="sortable" to any table you'd like to make sortable11 Click on the headers to sort12 13 Thanks to many, many people for contributions and suggestions.14 Licenced as X11: http://www.kryogenix.org/code/browser/licence.html15 This basically means: do what you want with it.16*/17 18var stIsIE = /*@cc_on!@*/ false;19 20sorttable = {21 init : function() {22 // quit if this function has already been called23 if (arguments.callee.done)24 return;25 // flag this function so we don't do the same thing twice26 arguments.callee.done = true;27 // kill the timer28 if (_timer)29 clearInterval(_timer);30 31 if (!document.createElement || !document.getElementsByTagName)32 return;33 34 sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;35 36 forEach(document.getElementsByTagName('table'), function(table) {37 if (table.className.search(/\bsortable\b/) != -1) {38 sorttable.makeSortable(table);39 }40 });41 },42 43 makeSortable : function(table) {44 if (table.getElementsByTagName('thead').length == 0) {45 // table doesn't have a tHead. Since it should have, create one and46 // put the first table row in it.47 the = document.createElement('thead');48 the.appendChild(table.rows[0]);49 table.insertBefore(the, table.firstChild);50 }51 // Safari doesn't support table.tHead, sigh52 if (table.tHead == null)53 table.tHead = table.getElementsByTagName('thead')[0];54 55 if (table.tHead.rows.length != 1)56 return; // can't cope with two header rows57 58 // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as59 // "total" rows, for example). This is B&R, since what you're supposed60 // to do is put them in a tfoot. So, if there are sortbottom rows,61 // for backward compatibility, move them to tfoot (creating it if needed).62 sortbottomrows = [];63 for (var i = 0; i < table.rows.length; i++) {64 if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {65 sortbottomrows[sortbottomrows.length] = table.rows[i];66 }67 }68 if (sortbottomrows) {69 if (table.tFoot == null) {70 // table doesn't have a tfoot. Create one.71 tfo = document.createElement('tfoot');72 table.appendChild(tfo);73 }74 for (var i = 0; i < sortbottomrows.length; i++) {75 tfo.appendChild(sortbottomrows[i]);76 }77 delete sortbottomrows;78 }79 80 // work through each column and calculate its type81 headrow = table.tHead.rows[0].cells;82 for (var i = 0; i < headrow.length; i++) {83 // manually override the type with a sorttable_type attribute84 if (!headrow[i].className.match(85 /\bsorttable_nosort\b/)) { // skip this col86 mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);87 if (mtch) {88 override = mtch[1];89 }90 if (mtch && typeof sorttable["sort_" + override] == 'function') {91 headrow[i].sorttable_sortfunction = sorttable["sort_" + override];92 } else {93 headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);94 }95 // make it clickable to sort96 headrow[i].sorttable_columnindex = i;97 headrow[i].sorttable_tbody = table.tBodies[0];98 dean_addEvent(headrow[i], "click", function(e) {99 if (this.className.search(/\bsorttable_sorted\b/) != -1) {100 // if we're already sorted by this column, just101 // reverse the table, which is quicker102 sorttable.reverse(this.sorttable_tbody);103 this.className = this.className.replace('sorttable_sorted',104 'sorttable_sorted_reverse');105 this.removeChild(document.getElementById('sorttable_sortfwdind'));106 sortrevind = document.createElement('span');107 sortrevind.id = "sorttable_sortrevind";108 sortrevind.innerHTML = stIsIE109 ? ' <font face="webdings">5</font>'110 : ' ▴';111 this.appendChild(sortrevind);112 return;113 }114 if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {115 // if we're already sorted by this column in reverse, just116 // re-reverse the table, which is quicker117 sorttable.reverse(this.sorttable_tbody);118 this.className = this.className.replace('sorttable_sorted_reverse',119 'sorttable_sorted');120 this.removeChild(document.getElementById('sorttable_sortrevind'));121 sortfwdind = document.createElement('span');122 sortfwdind.id = "sorttable_sortfwdind";123 sortfwdind.innerHTML = stIsIE124 ? ' <font face="webdings">6</font>'125 : ' ▾';126 this.appendChild(sortfwdind);127 return;128 }129 130 // remove sorttable_sorted classes131 theadrow = this.parentNode;132 forEach(theadrow.childNodes, function(cell) {133 if (cell.nodeType == 1) { // an element134 cell.className =135 cell.className.replace('sorttable_sorted_reverse', '');136 cell.className = cell.className.replace('sorttable_sorted', '');137 }138 });139 sortfwdind = document.getElementById('sorttable_sortfwdind');140 if (sortfwdind) {141 sortfwdind.parentNode.removeChild(sortfwdind);142 }143 sortrevind = document.getElementById('sorttable_sortrevind');144 if (sortrevind) {145 sortrevind.parentNode.removeChild(sortrevind);146 }147 148 this.className += ' sorttable_sorted';149 sortfwdind = document.createElement('span');150 sortfwdind.id = "sorttable_sortfwdind";151 sortfwdind.innerHTML =152 stIsIE ? ' <font face="webdings">6</font>' : ' ▾';153 this.appendChild(sortfwdind);154 155 // build an array to sort. This is a Schwartzian transform thing,156 // i.e., we "decorate" each row with the actual sort key,157 // sort based on the sort keys, and then put the rows back in order158 // which is a lot faster because you only do getInnerText once per row159 row_array = [];160 col = this.sorttable_columnindex;161 rows = this.sorttable_tbody.rows;162 for (var j = 0; j < rows.length; j++) {163 row_array[row_array.length] =164 [ sorttable.getInnerText(rows[j].cells[col]), rows[j] ];165 }166 /* If you want a stable sort, uncomment the following line */167 sorttable.shaker_sort(row_array, this.sorttable_sortfunction);168 /* and comment out this one */169 // row_array.sort(this.sorttable_sortfunction);170 171 tb = this.sorttable_tbody;172 for (var j = 0; j < row_array.length; j++) {173 tb.appendChild(row_array[j][1]);174 }175 176 delete row_array;177 });178 }179 }180 },181 182 guessType : function(table, column) {183 // guess the type of a column based on its first non-blank row184 sortfn = sorttable.sort_alpha;185 for (var i = 0; i < table.tBodies[0].rows.length; i++) {186 text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);187 if (text != '') {188 if (text.match(/^-?[」$、]?[\d,.]+%?$/)) {189 return sorttable.sort_numeric;190 }191 // check for a date: dd/mm/yyyy or dd/mm/yy192 // can have / or . or - as separator193 // can be mm/dd as well194 possdate = text.match(sorttable.DATE_RE)195 if (possdate) {196 // looks like a date197 first = parseInt(possdate[1]);198 second = parseInt(possdate[2]);199 if (first > 12) {200 // definitely dd/mm201 return sorttable.sort_ddmm;202 } else if (second > 12) {203 return sorttable.sort_mmdd;204 } else {205 // looks like a date, but we can't tell which, so assume206 // that it's dd/mm (English imperialism!) and keep looking207 sortfn = sorttable.sort_ddmm;208 }209 }210 }211 }212 return sortfn;213 },214 215 getInnerText : function(node) {216 // gets the text we want to use for sorting for a cell.217 // strips leading and trailing whitespace.218 // this is *not* a generic getInnerText function; it's special to sorttable.219 // for example, you can override the cell text with a customkey attribute.220 // it also gets .value for <input> fields.221 222 hasInputs = (typeof node.getElementsByTagName == 'function') &&223 node.getElementsByTagName('input').length;224 225 if (node.getAttribute("sorttable_customkey") != null) {226 return node.getAttribute("sorttable_customkey");227 } else if (typeof node.textContent != 'undefined' && !hasInputs) {228 return node.textContent.replace(/^\s+|\s+$/g, '');229 } else if (typeof node.innerText != 'undefined' && !hasInputs) {230 return node.innerText.replace(/^\s+|\s+$/g, '');231 } else if (typeof node.text != 'undefined' && !hasInputs) {232 return node.text.replace(/^\s+|\s+$/g, '');233 } else {234 switch (node.nodeType) {235 case 3:236 if (node.nodeName.toLowerCase() == 'input') {237 return node.value.replace(/^\s+|\s+$/g, '');238 }239 case 4:240 return node.nodeValue.replace(/^\s+|\s+$/g, '');241 break;242 case 1:243 case 11:244 var innerText = '';245 for (var i = 0; i < node.childNodes.length; i++) {246 innerText += sorttable.getInnerText(node.childNodes[i]);247 }248 return innerText.replace(/^\s+|\s+$/g, '');249 break;250 default:251 return '';252 }253 }254 },255 256 reverse : function(tbody) {257 // reverse the rows in a tbody258 newrows = [];259 for (var i = 0; i < tbody.rows.length; i++) {260 newrows[newrows.length] = tbody.rows[i];261 }262 for (var i = newrows.length - 1; i >= 0; i--) {263 tbody.appendChild(newrows[i]);264 }265 delete newrows;266 },267 268 /* sort functions269 each sort function takes two parameters, a and b270 you are comparing a[0] and b[0] */271 sort_numeric : function(a, b) {272 aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));273 if (isNaN(aa))274 aa = 0;275 bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));276 if (isNaN(bb))277 bb = 0;278 return aa - bb;279 },280 sort_alpha : function(a, b) {281 if (a[0] == b[0])282 return 0;283 if (a[0] < b[0])284 return -1;285 return 1;286 },287 sort_ddmm : function(a, b) {288 mtch = a[0].match(sorttable.DATE_RE);289 y = mtch[3];290 m = mtch[2];291 d = mtch[1];292 if (m.length == 1)293 m = '0' + m;294 if (d.length == 1)295 d = '0' + d;296 dt1 = y + m + d;297 mtch = b[0].match(sorttable.DATE_RE);298 y = mtch[3];299 m = mtch[2];300 d = mtch[1];301 if (m.length == 1)302 m = '0' + m;303 if (d.length == 1)304 d = '0' + d;305 dt2 = y + m + d;306 if (dt1 == dt2)307 return 0;308 if (dt1 < dt2)309 return -1;310 return 1;311 },312 sort_mmdd : function(a, b) {313 mtch = a[0].match(sorttable.DATE_RE);314 y = mtch[3];315 d = mtch[2];316 m = mtch[1];317 if (m.length == 1)318 m = '0' + m;319 if (d.length == 1)320 d = '0' + d;321 dt1 = y + m + d;322 mtch = b[0].match(sorttable.DATE_RE);323 y = mtch[3];324 d = mtch[2];325 m = mtch[1];326 if (m.length == 1)327 m = '0' + m;328 if (d.length == 1)329 d = '0' + d;330 dt2 = y + m + d;331 if (dt1 == dt2)332 return 0;333 if (dt1 < dt2)334 return -1;335 return 1;336 },337 338 shaker_sort : function(list, comp_func) {339 // A stable sort function to allow multi-level sorting of data340 // see: http://en.wikipedia.org/wiki/Cocktail_sort341 // thanks to Joseph Nahmias342 var b = 0;343 var t = list.length - 1;344 var swap = true;345 346 while (swap) {347 swap = false;348 for (var i = b; i < t; ++i) {349 if (comp_func(list[i], list[i + 1]) > 0) {350 var q = list[i];351 list[i] = list[i + 1];352 list[i + 1] = q;353 swap = true;354 }355 } // for356 t--;357 358 if (!swap)359 break;360 361 for (var i = t; i > b; --i) {362 if (comp_func(list[i], list[i - 1]) < 0) {363 var q = list[i];364 list[i] = list[i - 1];365 list[i - 1] = q;366 swap = true;367 }368 } // for369 b++;370 371 } // while(swap)372 }373}374 375/* ******************************************************************376 Supporting functions: bundled here to avoid depending on a library377 ****************************************************************** */378 379// Dean Edwards/Matthias Miller/John Resig380 381/* for Mozilla/Opera9 */382if (document.addEventListener) {383 document.addEventListener("DOMContentLoaded", sorttable.init, false);384}385 386/* for Internet Explorer */387/*@cc_on @*/388/*@if (@_win32)389 document.write("<script id=__ie_onload defer390src=javascript:void(0)><\/script>"); var script =391document.getElementById("__ie_onload"); script.onreadystatechange = function() {392 if (this.readyState == "complete") {393 sorttable.init(); // call the onload handler394 }395 };396/*@end @*/397 398/* for Safari */399if (/WebKit/i.test(navigator.userAgent)) { // sniff400 var _timer = setInterval(function() {401 if (/loaded|complete/.test(document.readyState)) {402 sorttable.init(); // call the onload handler403 }404 }, 10);405}406 407/* for other browsers */408window.onload = sorttable.init;409 410// written by Dean Edwards, 2005411// with input from Tino Zijdel, Matthias Miller, Diego Perini412 413// http://dean.edwards.name/weblog/2005/10/add-event/414 415function dean_addEvent(element, type, handler) {416 if (element.addEventListener) {417 element.addEventListener(type, handler, false);418 } else {419 // assign each event handler a unique ID420 if (!handler.$$guid)421 handler.$$guid = dean_addEvent.guid++;422 // create a hash table of event types for the element423 if (!element.events)424 element.events = {};425 // create a hash table of event handlers for each element/event pair426 var handlers = element.events[type];427 if (!handlers) {428 handlers = element.events[type] = {};429 // store the existing event handler (if there is one)430 if (element["on" + type]) {431 handlers[0] = element["on" + type];432 }433 }434 // store the event handler in the hash table435 handlers[handler.$$guid] = handler;436 // assign a global event handler to do all the work437 element["on" + type] = handleEvent;438 }439};440// a counter used to create unique IDs441dean_addEvent.guid = 1;442 443function removeEvent(element, type, handler) {444 if (element.removeEventListener) {445 element.removeEventListener(type, handler, false);446 } else {447 // delete the event handler from the hash table448 if (element.events && element.events[type]) {449 delete element.events[type][handler.$$guid];450 }451 }452};453 454function handleEvent(event) {455 var returnValue = true;456 // grab the event object (IE uses a global event object)457 event =458 event ||459 fixEvent(460 ((this.ownerDocument || this.document || this).parentWindow || window)461 .event);462 // get a reference to the hash table of event handlers463 var handlers = this.events[event.type];464 // execute each event handler465 for (var i in handlers) {466 this.$$handleEvent = handlers[i];467 if (this.$$handleEvent(event) === false) {468 returnValue = false;469 }470 }471 return returnValue;472};473 474function fixEvent(event) {475 // add W3C standard event methods476 event.preventDefault = fixEvent.preventDefault;477 event.stopPropagation = fixEvent.stopPropagation;478 return event;479};480fixEvent.preventDefault = function() { this.returnValue = false; };481fixEvent.stopPropagation = function() { this.cancelBubble = true; }482 483// Dean's forEach: http://dean.edwards.name/base/forEach.js484/*485 forEach, version 1.0486 Copyright 2006, Dean Edwards487 License: http://www.opensource.org/licenses/mit-license.php488*/489 490// array-like enumeration491if (!Array.forEach) { // mozilla already supports this492 Array.forEach = function(array, block, context) {493 for (var i = 0; i < array.length; i++) {494 block.call(context, array[i], i, array);495 }496 };497}498 499// generic enumeration500Function.prototype.forEach = function(object, block, context) {501 for (var key in object) {502 if (typeof this.prototype[key] == "undefined") {503 block.call(context, object[key], key, object);504 }505 }506};507 508// character enumeration509String.forEach = function(string, block, context) {510 Array.forEach(511 string.split(""),512 function(chr, index) { block.call(context, chr, index, string); });513};514 515// globally resolve forEach enumeration516var forEach = function(object, block, context) {517 if (object) {518 var resolve = Object; // default519 if (object instanceof Function) {520 // functions have a "length" property521 resolve = Function;522 } else if (object.forEach instanceof Function) {523 // the object implements a custom forEach method so use that524 object.forEach(block, context);525 return;526 } else if (typeof object == "string") {527 // the object is a string528 resolve = String;529 } else if (typeof object.length == "number") {530 // the object is array-like531 resolve = Array;532 }533 resolve.forEach(object, block, context);534 }535};