noalyss Version-9
sorttable.js
Go to the documentation of this file.
1/**
2 *
3 SortTable
4 version 2
5 7th April 2007
6 Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
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 @note
19 Documentation http://www.kryogenix.org/code/browser/sorttable/
20
21 Show the default order
22 example:
23 <th class=" sorttable_sorted_reverse">
24 ....<span id="sorttable_sortrevind">&nbsp;&blacktriangle;</span>
25<th class=" sorttable_sorted">
26
27 Sort on date
28 <td sorttable_customkey="<?=$row_bank['b_date']?>"> // format YYYYMMDD
29
30 force as numeric (normally useless):
31 <th class="sorttable_numeric">Part number</th>
32
33 Column to ignore : <th class="sorttable_nosort">
34 To avoid the sort on the last row, use tfoot
35
36 */
37
38
39var stIsIE = /*@cc_on!@*/false;
40
41var sorttable = {
42 init: function () {
43 // quit if this function has already been called
44 if (arguments.callee.done)
45 return;
46 // flag this function so we don't do the same thing twice
47 arguments.callee.done = true;
48 sorttable.icon_down='<span style="font-style: normal;vertical-align: super;\n' +
49 'padding: 2px;">&#9652;</span>';
50 sorttable.icon_up='<span style="font-style: normal;vertical-align: super;\n' +
51 'padding: 2px;">&#9662;</span>';
52
53 // kill the timer
54 if (_timer)
55 clearInterval(_timer);
56
57 if (!document.createElement || !document.getElementsByTagName)
58 return;
59
60 sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
61
62 forEach(document.getElementsByTagName('table'), function (table) {
63 if (table.className.search(/\bsortable\b/) != -1) {
64 sorttable.makeSortable(table);
65 }
66 });
67
68 },
69 makeSortable: function (table) {
70 if (table.getElementsByTagName('thead').length == 0) {
71 // table doesn't have a tHead. Since it should have, create one and
72 // put the first table row in it.
73 the = document.createElement('thead');
74 the.appendChild(table.rows[0]);
75 table.insertBefore(the, table.firstChild);
76 }
77 // Safari doesn't support table.tHead, sigh
78 if (table.tHead == null)
79 table.tHead = table.getElementsByTagName('thead')[0];
80
81 if (table.tHead.rows.length != 1)
82 return; // can't cope with two header rows
83
84 // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
85 // "total" rows, for example). This is B&R, since what you're supposed
86 // to do is put them in a tfoot. So, if there are sortbottom rows,
87 // for backwards compatibility, move them to tfoot (creating it if needed).
88 sortbottomrows = [];
89 for (var i = 0; i < table.rows.length; i++) {
90 if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
91 sortbottomrows[sortbottomrows.length] = table.rows[i];
92 }
93 }
94 if (sortbottomrows) {
95 if (table.tFoot == null) {
96 // table doesn't have a tfoot. Create one.
97 tfo = document.createElement('tfoot');
98 table.appendChild(tfo);
99 }
100 for (var i = 0; i < sortbottomrows.length; i++) {
101 tfo.appendChild(sortbottomrows[i]);
102 }
103 delete sortbottomrows;
104 }
105
106 // work through each column and calculate its type
107 var headrow = table.tHead.rows[0].cells;
108 for (var i = 0; i < headrow.length; i++) {
109 // manually override the type with a sorttable_type attribute
110 if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
111 mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
112 if (mtch) {
113 override = mtch[1];
114 }
115 if (mtch && typeof sorttable["sort_" + override] == 'function') {
116 headrow[i].sorttable_sortfunction = sorttable["sort_" + override];
117 } else {
118 headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);
119 }
120 //--------- if already sorted , add a icon but only if the icon is not yet there ----------------
121 if (headrow[i].className.search(/\bsorttable_sorted_reverse\b/) != -1 && headrow[i].innerHTML.search(/\bsorttable_sortrevind\b/)==-1) {
122
123 sortrevind = document.createElement('span');
124 sortrevind.id = "sorttable_sortrevind";
125 sortrevind.innerHTML = sorttable.icon_down;
126 headrow[i].appendChild(sortrevind);
127
128 }
129 if (headrow[i].className.search(/\bsorttable_sorted\b/) != -1 && headrow[i].innerHTML.search(/\bsorttable_sortfwdind\b/)==-1) {
130
131 sortfwdind = document.createElement('span');
132 sortfwdind.id = "sorttable_sortfwdind";
133 sortfwdind.innerHTML = sorttable.icon_up;
134 headrow[i].appendChild(sortfwdind);
135
136 }
137 // make it clickable to sort
138 headrow[i].sorttable_columnindex = i;
139 headrow[i].sorttable_tbody = table.tBodies[0];
140 dean_addEvent(headrow[i], "click", function (e) {
141
142 if (this.className.search(/\bsorttable_sorted\b/) != -1) {
143 // if we're already sorted by this column, just
144 // reverse the table, which is quicker
145 sorttable.reverse(this.sorttable_tbody);
146 this.className = this.className.replace('sorttable_sorted',
147 'sorttable_sorted_reverse');
148 this.removeChild(document.getElementById('sorttable_sortfwdind'));
149 sortrevind = document.createElement('span');
150 sortrevind.id = "sorttable_sortrevind";
151 // sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
152 sortrevind.innerHTML = sorttable.icon_down;
153 this.appendChild(sortrevind);
154 return;
155 }
156 if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
157 // if we're already sorted by this column in reverse, just
158 // re-reverse the table, which is quicker
159 sorttable.reverse(this.sorttable_tbody);
160 this.className = this.className.replace('sorttable_sorted_reverse',
161 'sorttable_sorted');
162 this.removeChild(document.getElementById('sorttable_sortrevind'));
163 sortfwdind = document.createElement('span');
164 sortfwdind.id = "sorttable_sortfwdind";
165// sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
166 sortfwdind.innerHTML = sorttable.icon_up;
167 this.appendChild(sortfwdind);
168 return;
169 }
170
171 // remove sorttable_sorted classes
172 theadrow = this.parentNode;
173 forEach(theadrow.childNodes, function (cell) {
174 if (cell.nodeType == 1) { // an element
175 cell.className = cell.className.replace('sorttable_sorted_reverse', '');
176 cell.className = cell.className.replace('sorttable_sorted', '');
177 }
178 });
179 sortfwdind = document.getElementById('sorttable_sortfwdind');
180 if (sortfwdind) {
181 sortfwdind.parentNode.removeChild(sortfwdind);
182 }
183 sortrevind = document.getElementById('sorttable_sortrevind');
184 if (sortrevind) {
185 sortrevind.parentNode.removeChild(sortrevind);
186 }
187
188 this.className += ' sorttable_sorted';
189 sortfwdind = document.createElement('span');
190 sortfwdind.id = "sorttable_sortfwdind";
191// sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
192 sortfwdind.innerHTML = sorttable.icon_up;
193 this.appendChild(sortfwdind);
194
195 // build an array to sort. This is a Schwartzian transform thing,
196 // i.e., we "decorate" each row with the actual sort key,
197 // sort based on the sort keys, and then put the rows back in order
198 // which is a lot faster because you only do getInnerText once per row
199 var row_array = [];
200 var col = this.sorttable_columnindex;
201 var rows = this.sorttable_tbody.rows;
202 for (var j = 0; j < rows.length; j++) {
203 row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
204 }
205 /* If you want a stable sort, uncomment the following line */
206 //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
207 /* and comment out this one */
208 row_array.sort(this.sorttable_sortfunction);
209
210 tb = this.sorttable_tbody;
211 for (var j = 0; j < row_array.length; j++) {
212 tb.appendChild(row_array[j][1]);
213 }
214 delete row_array;
215 // Highlight odd and even rows properly
216 sorttable.highlight_body(table);
217 });
218 }
219 }
220 },
221 /**
222 * alternate properly the rows of the table,
223 * @param {DOMNode} p_table sorted table
224 */
225 highlight_body:function(p_table) {
226 var nb_row=p_table.rows;
227 var e=0;
228 for (e=1;e<nb_row.length;e++) {
229 if (e % 2 == 0 ) {
230 if ( nb_row[e].className=="odd" ) nb_row[e].className="even";
231 } else {
232 if ( nb_row[e].className=="even" ) nb_row[e].className="odd";
233 }
234 }
235 },
236 guessType: function (table, column) {
237 // guess the type of a column based on its first non-blank row
238 sortfn = sorttable.sort_alpha;
239 for (var i = 0; i < table.tBodies[0].rows.length; i++) {
240 text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
241 if (text != '') {
242 if (text.match(/^-?[�$�]?[\d,.]+%?$/)) {
243 return sorttable.sort_numeric;
244 }
245 // check for a date: dd/mm/yyyy or dd/mm/yy
246 // can have / or . or - as separator
247 // can be mm/dd as well
248 possdate = text.match(sorttable.DATE_RE)
249 if (possdate) {
250 // looks like a date
251 first = parseInt(possdate[1]);
252 second = parseInt(possdate[2]);
253 if (first > 12) {
254 // definitely dd/mm
255 return sorttable.sort_ddmm;
256 } else if (second > 12) {
257 return sorttable.sort_mmdd;
258 } else {
259 // looks like a date, but we can't tell which, so assume
260 // that it's dd/mm (English imperialism!) and keep looking
261 sortfn = sorttable.sort_ddmm;
262 }
263 }
264 }
265 }
266 return sortfn;
267 },
268 getInnerText: function (node) {
269 // gets the text we want to use for sorting for a cell.
270 // strips leading and trailing whitespace.
271 // this is *not* a generic getInnerText function; it's special to sorttable.
272 // for example, you can override the cell text with a customkey attribute.
273 // it also gets .value for <input> fields.
274
275 if (!node)
276 return "";
277
278 hasInputs = (typeof node.getElementsByTagName == 'function') &&
279 node.getElementsByTagName('input').length;
280
281 if (node.getAttribute && node.getAttribute("sorttable_customkey") != null) {
282 return node.getAttribute("sorttable_customkey");
283 } else if (typeof node.textContent != 'undefined' && !hasInputs) {
284 return node.textContent.replace(/^\s+|\s+$/g, '');
285 } else if (typeof node.innerText != 'undefined' && !hasInputs) {
286 return node.innerText.replace(/^\s+|\s+$/g, '');
287 } else if (typeof node.text != 'undefined' && !hasInputs) {
288 return node.text.replace(/^\s+|\s+$/g, '');
289 } else {
290 switch (node.nodeType) {
291 case 3:
292 if (node.nodeName.toLowerCase() == 'input') {
293 return node.value.replace(/^\s+|\s+$/g, '');
294 }
295 case 4:
296 return node.nodeValue.replace(/^\s+|\s+$/g, '');
297 break;
298 case 1:
299 case 11:
300 var innerText = '';
301 for (var i = 0; i < node.childNodes.length; i++) {
302 innerText += sorttable.getInnerText(node.childNodes[i]);
303 }
304 return innerText.replace(/^\s+|\s+$/g, '');
305 break;
306 default:
307 return '';
308 }
309 }
310 },
311 reverse: function (tbody) {
312 // reverse the rows in a tbody
313 var newrows = [];
314 for (var i = 0; i < tbody.rows.length; i++) {
315 newrows[newrows.length] = tbody.rows[i];
316 }
317 for (var i = newrows.length - 1; i >= 0; i--) {
318 tbody.appendChild(newrows[i]);
319 }
320 delete newrows;
321 },
322 /* sort functions
323 each sort function takes two parameters, a and b
324 you are comparing a[0] and b[0] */
325 sort_numeric: function (a, b) {
326 var aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));
327 if (isNaN(aa))
328 aa = 0;
329 var bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));
330 if (isNaN(bb))
331 bb = 0;
332 return aa - bb;
333 },
334 sort_alpha: function (a, b) {
335 if (a[0] == b[0])
336 return 0;
337 if (a[0] < b[0])
338 return -1;
339 return 1;
340 },
341 sort_ddmm: function (a, b) {
342 mtch = a[0].match(sorttable.DATE_RE);
343 y = mtch[3];
344 m = mtch[2];
345 d = mtch[1];
346 if (m.length == 1)
347 m = '0' + m;
348 if (d.length == 1)
349 d = '0' + d;
350 dt1 = y + m + d;
351 mtch = b[0].match(sorttable.DATE_RE);
352 y = mtch[3];
353 m = mtch[2];
354 d = mtch[1];
355 if (m.length == 1)
356 m = '0' + m;
357 if (d.length == 1)
358 d = '0' + d;
359 dt2 = y + m + d;
360 if (dt1 == dt2)
361 return 0;
362 if (dt1 < dt2)
363 return -1;
364 return 1;
365 },
366 sort_mmdd: function (a, b) {
367 mtch = a[0].match(sorttable.DATE_RE);
368 y = mtch[3];
369 d = mtch[2];
370 m = mtch[1];
371 if (m.length == 1)
372 m = '0' + m;
373 if (d.length == 1)
374 d = '0' + d;
375 dt1 = y + m + d;
376 mtch = b[0].match(sorttable.DATE_RE);
377 y = mtch[3];
378 d = mtch[2];
379 m = mtch[1];
380 if (m.length == 1)
381 m = '0' + m;
382 if (d.length == 1)
383 d = '0' + d;
384 dt2 = y + m + d;
385 if (dt1 == dt2)
386 return 0;
387 if (dt1 < dt2)
388 return -1;
389 return 1;
390 },
391 shaker_sort: function (list, comp_func) {
392 // A stable sort function to allow multi-level sorting of data
393 // see: http://en.wikipedia.org/wiki/Cocktail_sort
394 // thanks to Joseph Nahmias
395 var b = 0;
396 var t = list.length - 1;
397 var swap = true;
398
399 while (swap) {
400 swap = false;
401 for (var i = b; i < t; ++i) {
402 if (comp_func(list[i], list[i + 1]) > 0) {
403 var q = list[i];
404 list[i] = list[i + 1];
405 list[i + 1] = q;
406 swap = true;
407 }
408 } // for
409 t--;
410
411 if (!swap)
412 break;
413
414 for (var i = t; i > b; --i) {
415 if (comp_func(list[i], list[i - 1]) < 0) {
416 var q = list[i];
417 list[i] = list[i - 1];
418 list[i - 1] = q;
419 swap = true;
420 }
421 } // for
422 b++;
423
424 } // while(swap)
425 }
426}
427
428/* ******************************************************************
429 Supporting functions: bundled here to avoid depending on a library
430 ****************************************************************** */
431
432// Dean Edwards/Matthias Miller/John Resig
433
434/* for Mozilla/Opera9 */
435if (document.addEventListener) {
436 document.addEventListener("DOMContentLoaded", sorttable.init, false);
437}
438
439/* for Internet Explorer */
440/*@cc_on @*/
441/*@if (@_win32)
442 document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
443 var script = document.getElementById("__ie_onload");
444 script.onreadystatechange = function() {
445 if (this.readyState == "complete") {
446 sorttable.init(); // call the onload handler
447 }
448 };
449 /*@end @*/
450
451/* for Safari */
452if (/WebKit/i.test(navigator.userAgent)) { // sniff
453 var _timer = setInterval(function () {
454 if (/loaded|complete/.test(document.readyState)) {
455 sorttable.init(); // call the onload handler
456 }
457 }, 10);
458}
459
460/* for other browsers */
461// Moved into noalyss_script.js
462//window.onload = sorttable.init;
463
464// written by Dean Edwards, 2005
465// with input from Tino Zijdel, Matthias Miller, Diego Perini
466
467// http://dean.edwards.name/weblog/2005/10/add-event/
468
469function dean_addEvent(element, type, handler) {
470 if (element.addEventListener) {
471 element.addEventListener(type, handler, false);
472 } else {
473 // assign each event handler a unique ID
474 if (!handler.$$guid)
475 handler.$$guid = dean_addEvent.guid++;
476 // create a hash table of event types for the element
477 if (!element.events)
478 element.events = {};
479 // create a hash table of event handlers for each element/event pair
480 var handlers = element.events[type];
481 if (!handlers) {
482 handlers = element.events[type] = {};
483 // store the existing event handler (if there is one)
484 if (element["on" + type]) {
485 handlers[0] = element["on" + type];
486 }
487 }
488 // store the event handler in the hash table
489 handlers[handler.$$guid] = handler;
490 // assign a global event handler to do all the work
491 element["on" + type] = handleEvent;
492 }
493}
494;
495// a counter used to create unique IDs
496dean_addEvent.guid = 1;
497
498function removeEvent(element, type, handler) {
499 if (element.removeEventListener) {
500 element.removeEventListener(type, handler, false);
501 } else {
502 // delete the event handler from the hash table
503 if (element.events && element.events[type]) {
504 delete element.events[type][handler.$$guid];
505 }
506 }
507}
508;
509
510function handleEvent(event) {
511 var returnValue = true;
512 // grab the event object (IE uses a global event object)
513 event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
514 // get a reference to the hash table of event handlers
515 var handlers = this.events[event.type];
516 // execute each event handler
517 for (var i in handlers) {
518 this.$$handleEvent = handlers[i];
519 if (this.$$handleEvent(event) === false) {
520 returnValue = false;
521 }
522 }
523 return returnValue;
524}
525;
526
527function fixEvent(event) {
528 // add W3C standard event methods
529 event.preventDefault = fixEvent.preventDefault;
530 event.stopPropagation = fixEvent.stopPropagation;
531 return event;
532}
533;
534fixEvent.preventDefault = function () {
535 this.returnValue = false;
536};
537fixEvent.stopPropagation = function () {
538 this.cancelBubble = true;
539}
540
541// Dean's forEach: http://dean.edwards.name/base/forEach.js
542/*
543 forEach, version 1.0
544 Copyright 2006, Dean Edwards
545 License: http://www.opensource.org/licenses/mit-license.php
546 */
547
548// array-like enumeration
549if (!Array.forEach) { // mozilla already supports this
550 Array.forEach = function (array, block, context) {
551 for (var i = 0; i < array.length; i++) {
552 block.call(context, array[i], i, array);
553 }
554 };
555}
556
557// generic enumeration
558Function.prototype.forEach = function (object, block, context) {
559 for (var key in object) {
560 if (typeof this.prototype[key] == "undefined") {
561 block.call(context, object[key], key, object);
562 }
563 }
564};
565
566// character enumeration
567String.forEach = function (string, block, context) {
568 Array.forEach(string.split(""), function (chr, index) {
569 block.call(context, chr, index, string);
570 });
571};
572
573// globally resolve forEach enumeration
574var forEach = function (object, block, context) {
575 if (object) {
576 var resolve = Object; // default
577 if (object instanceof Function) {
578 // functions have a "length" property
579 resolve = Function;
580 } else if (object.forEach instanceof Function) {
581 // the object implements a custom forEach method so use that
582 object.forEach(block, context);
583 return;
584 } else if (typeof object == "string") {
585 // the object is a string
586 resolve = String;
587 } else if (typeof object.length == "number") {
588 // the object is array-like
589 resolve = Array;
590 }
591 resolve.forEach(object, block, context);
592 }
593};
594