sorttable.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. SortTable
  3. version 2
  4. 7th April 2007
  5. Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
  6. Instructions:
  7. Download this file
  8. Add <script src="sorttable.js"></script> to your HTML
  9. Add class="sortable" to any table you'd like to make sortable
  10. Click on the headers to sort
  11. Thanks to many, many people for contributions and suggestions.
  12. Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
  13. This basically means: do what you want with it.
  14. */
  15. var stIsIE = /*@cc_on!@*/false;
  16. sorttable = {
  17. init: function() {
  18. // quit if this function has already been called
  19. if (arguments.callee.done) return;
  20. // flag this function so we don't do the same thing twice
  21. arguments.callee.done = true;
  22. // kill the timer
  23. if (_timer) clearInterval(_timer);
  24. if (!document.createElement || !document.getElementsByTagName) return;
  25. sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
  26. forEach(document.getElementsByTagName('table'), function(table) {
  27. if (table.className.search(/\bsortable\b/) != -1) {
  28. sorttable.makeSortable(table);
  29. }
  30. });
  31. },
  32. makeSortable: function(table) {
  33. if (table.getElementsByTagName('thead').length == 0) {
  34. // table doesn't have a tHead. Since it should have, create one and
  35. // put the first table row in it.
  36. the = document.createElement('thead');
  37. the.appendChild(table.rows[0]);
  38. table.insertBefore(the,table.firstChild);
  39. }
  40. // Safari doesn't support table.tHead, sigh
  41. if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
  42. if (table.tHead.rows.length != 1) return; // can't cope with two header rows
  43. // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
  44. // "total" rows, for example). This is B&R, since what you're supposed
  45. // to do is put them in a tfoot. So, if there are sortbottom rows,
  46. // for backwards compatibility, move them to tfoot (creating it if needed).
  47. sortbottomrows = [];
  48. for (var i=0; i<table.rows.length; i++) {
  49. if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
  50. sortbottomrows[sortbottomrows.length] = table.rows[i];
  51. }
  52. }
  53. if (sortbottomrows) {
  54. if (table.tFoot == null) {
  55. // table doesn't have a tfoot. Create one.
  56. tfo = document.createElement('tfoot');
  57. table.appendChild(tfo);
  58. }
  59. for (var i=0; i<sortbottomrows.length; i++) {
  60. tfo.appendChild(sortbottomrows[i]);
  61. }
  62. delete sortbottomrows;
  63. }
  64. // work through each column and calculate its type
  65. headrow = table.tHead.rows[0].cells;
  66. for (var i=0; i<headrow.length; i++) {
  67. // manually override the type with a sorttable_type attribute
  68. if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
  69. mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
  70. if (mtch) { override = mtch[1]; }
  71. if (mtch && typeof sorttable["sort_"+override] == 'function') {
  72. headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
  73. } else {
  74. headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
  75. }
  76. // make it clickable to sort
  77. headrow[i].sorttable_columnindex = i;
  78. headrow[i].sorttable_tbody = table.tBodies[0];
  79. dean_addEvent(headrow[i],"click", function(e) {
  80. if (this.className.search(/\bsorttable_sorted\b/) != -1) {
  81. // if we're already sorted by this column, just
  82. // reverse the table, which is quicker
  83. sorttable.reverse(this.sorttable_tbody);
  84. this.className = this.className.replace('sorttable_sorted',
  85. 'sorttable_sorted_reverse');
  86. this.removeChild(document.getElementById('sorttable_sortfwdind'));
  87. sortrevind = document.createElement('span');
  88. sortrevind.id = "sorttable_sortrevind";
  89. sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
  90. this.appendChild(sortrevind);
  91. return;
  92. }
  93. if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
  94. // if we're already sorted by this column in reverse, just
  95. // re-reverse the table, which is quicker
  96. sorttable.reverse(this.sorttable_tbody);
  97. this.className = this.className.replace('sorttable_sorted_reverse',
  98. 'sorttable_sorted');
  99. this.removeChild(document.getElementById('sorttable_sortrevind'));
  100. sortfwdind = document.createElement('span');
  101. sortfwdind.id = "sorttable_sortfwdind";
  102. sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
  103. this.appendChild(sortfwdind);
  104. return;
  105. }
  106. // remove sorttable_sorted classes
  107. theadrow = this.parentNode;
  108. forEach(theadrow.childNodes, function(cell) {
  109. if (cell.nodeType == 1) { // an element
  110. cell.className = cell.className.replace('sorttable_sorted_reverse','');
  111. cell.className = cell.className.replace('sorttable_sorted','');
  112. }
  113. });
  114. sortfwdind = document.getElementById('sorttable_sortfwdind');
  115. if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
  116. sortrevind = document.getElementById('sorttable_sortrevind');
  117. if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
  118. this.className += ' sorttable_sorted';
  119. sortfwdind = document.createElement('span');
  120. sortfwdind.id = "sorttable_sortfwdind";
  121. sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
  122. this.appendChild(sortfwdind);
  123. // build an array to sort. This is a Schwartzian transform thing,
  124. // i.e., we "decorate" each row with the actual sort key,
  125. // sort based on the sort keys, and then put the rows back in order
  126. // which is a lot faster because you only do getInnerText once per row
  127. row_array = [];
  128. col = this.sorttable_columnindex;
  129. rows = this.sorttable_tbody.rows;
  130. for (var j=0; j<rows.length; j++) {
  131. row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
  132. }
  133. /* If you want a stable sort, uncomment the following line */
  134. //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
  135. /* and comment out this one */
  136. row_array.sort(this.sorttable_sortfunction);
  137. tb = this.sorttable_tbody;
  138. for (var j=0; j<row_array.length; j++) {
  139. tb.appendChild(row_array[j][1]);
  140. }
  141. delete row_array;
  142. });
  143. }
  144. }
  145. },
  146. guessType: function(table, column) {
  147. // guess the type of a column based on its first non-blank row
  148. sortfn = sorttable.sort_alpha;
  149. for (var i=0; i<table.tBodies[0].rows.length; i++) {
  150. text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
  151. if (text != '') {
  152. if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
  153. return sorttable.sort_numeric;
  154. }
  155. // check for a date: dd/mm/yyyy or dd/mm/yy
  156. // can have / or . or - as separator
  157. // can be mm/dd as well
  158. possdate = text.match(sorttable.DATE_RE)
  159. if (possdate) {
  160. // looks like a date
  161. first = parseInt(possdate[1]);
  162. second = parseInt(possdate[2]);
  163. if (first > 12) {
  164. // definitely dd/mm
  165. return sorttable.sort_ddmm;
  166. } else if (second > 12) {
  167. return sorttable.sort_mmdd;
  168. } else {
  169. // looks like a date, but we can't tell which, so assume
  170. // that it's dd/mm (English imperialism!) and keep looking
  171. sortfn = sorttable.sort_ddmm;
  172. }
  173. }
  174. }
  175. }
  176. return sortfn;
  177. },
  178. getInnerText: function(node) {
  179. // gets the text we want to use for sorting for a cell.
  180. // strips leading and trailing whitespace.
  181. // this is *not* a generic getInnerText function; it's special to sorttable.
  182. // for example, you can override the cell text with a customkey attribute.
  183. // it also gets .value for <input> fields.
  184. hasInputs = (typeof node.getElementsByTagName == 'function') &&
  185. node.getElementsByTagName('input').length;
  186. if (node.nodeType == 1 && node.getAttribute("sorttable_customkey") != null) {
  187. return node.getAttribute("sorttable_customkey");
  188. }
  189. else if (typeof node.textContent != 'undefined' && !hasInputs) {
  190. return node.textContent.replace(/^\s+|\s+$/g, '');
  191. }
  192. else if (typeof node.innerText != 'undefined' && !hasInputs) {
  193. return node.innerText.replace(/^\s+|\s+$/g, '');
  194. }
  195. else if (typeof node.text != 'undefined' && !hasInputs) {
  196. return node.text.replace(/^\s+|\s+$/g, '');
  197. }
  198. else {
  199. switch (node.nodeType) {
  200. case 3:
  201. if (node.nodeName.toLowerCase() == 'input') {
  202. return node.value.replace(/^\s+|\s+$/g, '');
  203. }
  204. case 4:
  205. return node.nodeValue.replace(/^\s+|\s+$/g, '');
  206. break;
  207. case 1:
  208. case 11:
  209. var innerText = '';
  210. for (var i = 0; i < node.childNodes.length; i++) {
  211. innerText += sorttable.getInnerText(node.childNodes[i]);
  212. }
  213. return innerText.replace(/^\s+|\s+$/g, '');
  214. break;
  215. default:
  216. return '';
  217. }
  218. }
  219. },
  220. reverse: function(tbody) {
  221. // reverse the rows in a tbody
  222. newrows = [];
  223. for (var i=0; i<tbody.rows.length; i++) {
  224. newrows[newrows.length] = tbody.rows[i];
  225. }
  226. for (var i=newrows.length-1; i>=0; i--) {
  227. tbody.appendChild(newrows[i]);
  228. }
  229. delete newrows;
  230. },
  231. /* sort functions
  232. each sort function takes two parameters, a and b
  233. you are comparing a[0] and b[0] */
  234. sort_numeric: function(a,b) {
  235. aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
  236. if (isNaN(aa)) aa = 0;
  237. bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
  238. if (isNaN(bb)) bb = 0;
  239. return aa-bb;
  240. },
  241. sort_alpha: function(a,b) {
  242. if (a[0]==b[0]) return 0;
  243. if (a[0]<b[0]) return -1;
  244. return 1;
  245. },
  246. sort_ddmm: function(a,b) {
  247. mtch = a[0].match(sorttable.DATE_RE);
  248. y = mtch[3]; m = mtch[2]; d = mtch[1];
  249. if (m.length == 1) m = '0'+m;
  250. if (d.length == 1) d = '0'+d;
  251. dt1 = y+m+d;
  252. mtch = b[0].match(sorttable.DATE_RE);
  253. y = mtch[3]; m = mtch[2]; d = mtch[1];
  254. if (m.length == 1) m = '0'+m;
  255. if (d.length == 1) d = '0'+d;
  256. dt2 = y+m+d;
  257. if (dt1==dt2) return 0;
  258. if (dt1<dt2) return -1;
  259. return 1;
  260. },
  261. sort_mmdd: function(a,b) {
  262. mtch = a[0].match(sorttable.DATE_RE);
  263. y = mtch[3]; d = mtch[2]; m = mtch[1];
  264. if (m.length == 1) m = '0'+m;
  265. if (d.length == 1) d = '0'+d;
  266. dt1 = y+m+d;
  267. mtch = b[0].match(sorttable.DATE_RE);
  268. y = mtch[3]; d = mtch[2]; m = mtch[1];
  269. if (m.length == 1) m = '0'+m;
  270. if (d.length == 1) d = '0'+d;
  271. dt2 = y+m+d;
  272. if (dt1==dt2) return 0;
  273. if (dt1<dt2) return -1;
  274. return 1;
  275. },
  276. shaker_sort: function(list, comp_func) {
  277. // A stable sort function to allow multi-level sorting of data
  278. // see: http://en.wikipedia.org/wiki/Cocktail_sort
  279. // thanks to Joseph Nahmias
  280. var b = 0;
  281. var t = list.length - 1;
  282. var swap = true;
  283. while(swap) {
  284. swap = false;
  285. for(var i = b; i < t; ++i) {
  286. if ( comp_func(list[i], list[i+1]) > 0 ) {
  287. var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
  288. swap = true;
  289. }
  290. } // for
  291. t--;
  292. if (!swap) break;
  293. for(var i = t; i > b; --i) {
  294. if ( comp_func(list[i], list[i-1]) < 0 ) {
  295. var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
  296. swap = true;
  297. }
  298. } // for
  299. b++;
  300. } // while(swap)
  301. }
  302. }
  303. /* ******************************************************************
  304. Supporting functions: bundled here to avoid depending on a library
  305. ****************************************************************** */
  306. // Dean Edwards/Matthias Miller/John Resig
  307. /* for Mozilla/Opera9 */
  308. if (document.addEventListener) {
  309. document.addEventListener("DOMContentLoaded", sorttable.init, false);
  310. }
  311. /* for Internet Explorer */
  312. /*@cc_on @*/
  313. /*@if (@_win32)
  314. document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  315. var script = document.getElementById("__ie_onload");
  316. script.onreadystatechange = function() {
  317. if (this.readyState == "complete") {
  318. sorttable.init(); // call the onload handler
  319. }
  320. };
  321. /*@end @*/
  322. /* for Safari */
  323. if (/WebKit/i.test(navigator.userAgent)) { // sniff
  324. var _timer = setInterval(function() {
  325. if (/loaded|complete/.test(document.readyState)) {
  326. sorttable.init(); // call the onload handler
  327. }
  328. }, 10);
  329. }
  330. /* for other browsers */
  331. window.onload = sorttable.init;
  332. // written by Dean Edwards, 2005
  333. // with input from Tino Zijdel, Matthias Miller, Diego Perini
  334. // http://dean.edwards.name/weblog/2005/10/add-event/
  335. function dean_addEvent(element, type, handler) {
  336. if (element.addEventListener) {
  337. element.addEventListener(type, handler, false);
  338. } else {
  339. // assign each event handler a unique ID
  340. if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
  341. // create a hash table of event types for the element
  342. if (!element.events) element.events = {};
  343. // create a hash table of event handlers for each element/event pair
  344. var handlers = element.events[type];
  345. if (!handlers) {
  346. handlers = element.events[type] = {};
  347. // store the existing event handler (if there is one)
  348. if (element["on" + type]) {
  349. handlers[0] = element["on" + type];
  350. }
  351. }
  352. // store the event handler in the hash table
  353. handlers[handler.$$guid] = handler;
  354. // assign a global event handler to do all the work
  355. element["on" + type] = handleEvent;
  356. }
  357. };
  358. // a counter used to create unique IDs
  359. dean_addEvent.guid = 1;
  360. function removeEvent(element, type, handler) {
  361. if (element.removeEventListener) {
  362. element.removeEventListener(type, handler, false);
  363. } else {
  364. // delete the event handler from the hash table
  365. if (element.events && element.events[type]) {
  366. delete element.events[type][handler.$$guid];
  367. }
  368. }
  369. };
  370. function handleEvent(event) {
  371. var returnValue = true;
  372. // grab the event object (IE uses a global event object)
  373. event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
  374. // get a reference to the hash table of event handlers
  375. var handlers = this.events[event.type];
  376. // execute each event handler
  377. for (var i in handlers) {
  378. this.$$handleEvent = handlers[i];
  379. if (this.$$handleEvent(event) === false) {
  380. returnValue = false;
  381. }
  382. }
  383. return returnValue;
  384. };
  385. function fixEvent(event) {
  386. // add W3C standard event methods
  387. event.preventDefault = fixEvent.preventDefault;
  388. event.stopPropagation = fixEvent.stopPropagation;
  389. return event;
  390. };
  391. fixEvent.preventDefault = function() {
  392. this.returnValue = false;
  393. };
  394. fixEvent.stopPropagation = function() {
  395. this.cancelBubble = true;
  396. }
  397. // Dean's forEach: http://dean.edwards.name/base/forEach.js
  398. /*
  399. forEach, version 1.0
  400. Copyright 2006, Dean Edwards
  401. License: http://www.opensource.org/licenses/mit-license.php
  402. */
  403. // array-like enumeration
  404. if (!Array.forEach) { // mozilla already supports this
  405. Array.forEach = function(array, block, context) {
  406. for (var i = 0; i < array.length; i++) {
  407. block.call(context, array[i], i, array);
  408. }
  409. };
  410. }
  411. // generic enumeration
  412. Function.prototype.forEach = function(object, block, context) {
  413. for (var key in object) {
  414. if (typeof this.prototype[key] == "undefined") {
  415. block.call(context, object[key], key, object);
  416. }
  417. }
  418. };
  419. // character enumeration
  420. String.forEach = function(string, block, context) {
  421. Array.forEach(string.split(""), function(chr, index) {
  422. block.call(context, chr, index, string);
  423. });
  424. };
  425. // globally resolve forEach enumeration
  426. var forEach = function(object, block, context) {
  427. if (object) {
  428. var resolve = Object; // default
  429. if (object instanceof Function) {
  430. // functions have a "length" property
  431. resolve = Function;
  432. } else if (object.forEach instanceof Function) {
  433. // the object implements a custom forEach method so use that
  434. object.forEach(block, context);
  435. return;
  436. } else if (typeof object == "string") {
  437. // the object is a string
  438. resolve = String;
  439. } else if (typeof object.length == "number") {
  440. // the object is array-like
  441. resolve = Array;
  442. }
  443. resolve.forEach(object, block, context);
  444. }
  445. };