Advertisement
Guest User

Untitled

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