logo

blog

My website can't be that messy, right? git clone https://hacktivis.me/git/blog.git

sorttable.js (16877B)


  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", sorttable.innerSortFunction = 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. if (!node) return "";
  185. hasInputs = (typeof node.getElementsByTagName == 'function') &&
  186. node.getElementsByTagName('input').length;
  187. if (node.getAttribute("sorttable_customkey") != null) {
  188. return node.getAttribute("sorttable_customkey");
  189. }
  190. else if (typeof node.textContent != 'undefined' && !hasInputs) {
  191. return node.textContent.replace(/^\s+|\s+$/g, '');
  192. }
  193. else if (typeof node.innerText != 'undefined' && !hasInputs) {
  194. return node.innerText.replace(/^\s+|\s+$/g, '');
  195. }
  196. else if (typeof node.text != 'undefined' && !hasInputs) {
  197. return node.text.replace(/^\s+|\s+$/g, '');
  198. }
  199. else {
  200. switch (node.nodeType) {
  201. case 3:
  202. if (node.nodeName.toLowerCase() == 'input') {
  203. return node.value.replace(/^\s+|\s+$/g, '');
  204. }
  205. case 4:
  206. return node.nodeValue.replace(/^\s+|\s+$/g, '');
  207. break;
  208. case 1:
  209. case 11:
  210. var innerText = '';
  211. for (var i = 0; i < node.childNodes.length; i++) {
  212. innerText += sorttable.getInnerText(node.childNodes[i]);
  213. }
  214. return innerText.replace(/^\s+|\s+$/g, '');
  215. break;
  216. default:
  217. return '';
  218. }
  219. }
  220. },
  221. reverse: function(tbody) {
  222. // reverse the rows in a tbody
  223. newrows = [];
  224. for (var i=0; i<tbody.rows.length; i++) {
  225. newrows[newrows.length] = tbody.rows[i];
  226. }
  227. for (var i=newrows.length-1; i>=0; i--) {
  228. tbody.appendChild(newrows[i]);
  229. }
  230. delete newrows;
  231. },
  232. /* sort functions
  233. each sort function takes two parameters, a and b
  234. you are comparing a[0] and b[0] */
  235. sort_numeric: function(a,b) {
  236. aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
  237. if (isNaN(aa)) aa = 0;
  238. bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
  239. if (isNaN(bb)) bb = 0;
  240. return aa-bb;
  241. },
  242. sort_alpha: function(a,b) {
  243. if (a[0]==b[0]) return 0;
  244. if (a[0]<b[0]) return -1;
  245. return 1;
  246. },
  247. sort_ddmm: function(a,b) {
  248. mtch = a[0].match(sorttable.DATE_RE);
  249. y = mtch[3]; m = mtch[2]; d = mtch[1];
  250. if (m.length == 1) m = '0'+m;
  251. if (d.length == 1) d = '0'+d;
  252. dt1 = y+m+d;
  253. mtch = b[0].match(sorttable.DATE_RE);
  254. y = mtch[3]; m = mtch[2]; d = mtch[1];
  255. if (m.length == 1) m = '0'+m;
  256. if (d.length == 1) d = '0'+d;
  257. dt2 = y+m+d;
  258. if (dt1==dt2) return 0;
  259. if (dt1<dt2) return -1;
  260. return 1;
  261. },
  262. sort_mmdd: function(a,b) {
  263. mtch = a[0].match(sorttable.DATE_RE);
  264. y = mtch[3]; d = mtch[2]; m = mtch[1];
  265. if (m.length == 1) m = '0'+m;
  266. if (d.length == 1) d = '0'+d;
  267. dt1 = y+m+d;
  268. mtch = b[0].match(sorttable.DATE_RE);
  269. y = mtch[3]; d = mtch[2]; m = mtch[1];
  270. if (m.length == 1) m = '0'+m;
  271. if (d.length == 1) d = '0'+d;
  272. dt2 = y+m+d;
  273. if (dt1==dt2) return 0;
  274. if (dt1<dt2) return -1;
  275. return 1;
  276. },
  277. shaker_sort: function(list, comp_func) {
  278. // A stable sort function to allow multi-level sorting of data
  279. // see: http://en.wikipedia.org/wiki/Cocktail_sort
  280. // thanks to Joseph Nahmias
  281. var b = 0;
  282. var t = list.length - 1;
  283. var swap = true;
  284. while(swap) {
  285. swap = false;
  286. for(var i = b; i < t; ++i) {
  287. if ( comp_func(list[i], list[i+1]) > 0 ) {
  288. var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
  289. swap = true;
  290. }
  291. } // for
  292. t--;
  293. if (!swap) break;
  294. for(var i = t; i > b; --i) {
  295. if ( comp_func(list[i], list[i-1]) < 0 ) {
  296. var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
  297. swap = true;
  298. }
  299. } // for
  300. b++;
  301. } // while(swap)
  302. }
  303. }
  304. /* ******************************************************************
  305. Supporting functions: bundled here to avoid depending on a library
  306. ****************************************************************** */
  307. // Dean Edwards/Matthias Miller/John Resig
  308. /* for Mozilla/Opera9 */
  309. if (document.addEventListener) {
  310. document.addEventListener("DOMContentLoaded", sorttable.init, false);
  311. }
  312. /* for Internet Explorer */
  313. /*@cc_on @*/
  314. /*@if (@_win32)
  315. document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  316. var script = document.getElementById("__ie_onload");
  317. script.onreadystatechange = function() {
  318. if (this.readyState == "complete") {
  319. sorttable.init(); // call the onload handler
  320. }
  321. };
  322. /*@end @*/
  323. /* for Safari */
  324. if (/WebKit/i.test(navigator.userAgent)) { // sniff
  325. var _timer = setInterval(function() {
  326. if (/loaded|complete/.test(document.readyState)) {
  327. sorttable.init(); // call the onload handler
  328. }
  329. }, 10);
  330. }
  331. /* for other browsers */
  332. window.onload = sorttable.init;
  333. // written by Dean Edwards, 2005
  334. // with input from Tino Zijdel, Matthias Miller, Diego Perini
  335. // http://dean.edwards.name/weblog/2005/10/add-event/
  336. function dean_addEvent(element, type, handler) {
  337. if (element.addEventListener) {
  338. element.addEventListener(type, handler, false);
  339. } else {
  340. // assign each event handler a unique ID
  341. if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
  342. // create a hash table of event types for the element
  343. if (!element.events) element.events = {};
  344. // create a hash table of event handlers for each element/event pair
  345. var handlers = element.events[type];
  346. if (!handlers) {
  347. handlers = element.events[type] = {};
  348. // store the existing event handler (if there is one)
  349. if (element["on" + type]) {
  350. handlers[0] = element["on" + type];
  351. }
  352. }
  353. // store the event handler in the hash table
  354. handlers[handler.$$guid] = handler;
  355. // assign a global event handler to do all the work
  356. element["on" + type] = handleEvent;
  357. }
  358. };
  359. // a counter used to create unique IDs
  360. dean_addEvent.guid = 1;
  361. function removeEvent(element, type, handler) {
  362. if (element.removeEventListener) {
  363. element.removeEventListener(type, handler, false);
  364. } else {
  365. // delete the event handler from the hash table
  366. if (element.events && element.events[type]) {
  367. delete element.events[type][handler.$$guid];
  368. }
  369. }
  370. };
  371. function handleEvent(event) {
  372. var returnValue = true;
  373. // grab the event object (IE uses a global event object)
  374. event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
  375. // get a reference to the hash table of event handlers
  376. var handlers = this.events[event.type];
  377. // execute each event handler
  378. for (var i in handlers) {
  379. this.$$handleEvent = handlers[i];
  380. if (this.$$handleEvent(event) === false) {
  381. returnValue = false;
  382. }
  383. }
  384. return returnValue;
  385. };
  386. function fixEvent(event) {
  387. // add W3C standard event methods
  388. event.preventDefault = fixEvent.preventDefault;
  389. event.stopPropagation = fixEvent.stopPropagation;
  390. return event;
  391. };
  392. fixEvent.preventDefault = function() {
  393. this.returnValue = false;
  394. };
  395. fixEvent.stopPropagation = function() {
  396. this.cancelBubble = true;
  397. }
  398. // Dean's forEach: http://dean.edwards.name/base/forEach.js
  399. /*
  400. forEach, version 1.0
  401. Copyright 2006, Dean Edwards
  402. License: http://www.opensource.org/licenses/mit-license.php
  403. */
  404. // array-like enumeration
  405. if (!Array.forEach) { // mozilla already supports this
  406. Array.forEach = function(array, block, context) {
  407. for (var i = 0; i < array.length; i++) {
  408. block.call(context, array[i], i, array);
  409. }
  410. };
  411. }
  412. // generic enumeration
  413. Function.prototype.forEach = function(object, block, context) {
  414. for (var key in object) {
  415. if (typeof this.prototype[key] == "undefined") {
  416. block.call(context, object[key], key, object);
  417. }
  418. }
  419. };
  420. // character enumeration
  421. String.forEach = function(string, block, context) {
  422. Array.forEach(string.split(""), function(chr, index) {
  423. block.call(context, chr, index, string);
  424. });
  425. };
  426. // globally resolve forEach enumeration
  427. var forEach = function(object, block, context) {
  428. if (object) {
  429. var resolve = Object; // default
  430. if (object instanceof Function) {
  431. // functions have a "length" property
  432. resolve = Function;
  433. } else if (object.forEach instanceof Function) {
  434. // the object implements a custom forEach method so use that
  435. object.forEach(block, context);
  436. return;
  437. } else if (typeof object == "string") {
  438. // the object is a string
  439. resolve = String;
  440. } else if (typeof object.length == "number") {
  441. // the object is array-like
  442. resolve = Array;
  443. }
  444. resolve.forEach(object, block, context);
  445. }
  446. };