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