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