6 Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
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
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.
19 Documentation http://www.kryogenix.org/code/browser/sorttable/
21 Show the default order
23 <th class=" sorttable_sorted_reverse">
24 ....<span id="sorttable_sortrevind"> ▴</span>
25<th class=" sorttable_sorted">
28 <td sorttable_customkey="<?=$row_bank['b_date']?>"> // format YYYYMMDD
30 force as numeric (normally useless):
31 <th class="sorttable_numeric">Part number</th>
33 Column to ignore : <th class="sorttable_nosort">
34 To avoid the sort on the last row, use tfoot
39var stIsIE = /*@cc_on!@*/false;
43 // quit if this function has already been called
44 if (arguments.callee.done)
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;">▴</span>';
50 sorttable.icon_up='<span style="font-style: normal;vertical-align: super;\n' +
51 'padding: 2px;">▾</span>';
55 clearInterval(_timer);
57 if (!document.createElement || !document.getElementsByTagName)
60 sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
62 forEach(document.getElementsByTagName('table'), function (table) {
63 if (table.className.search(/\bsortable\b/) != -1) {
64 sorttable.makeSortable(table);
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);
77 // Safari doesn't support table.tHead, sigh
78 if (table.tHead == null)
79 table.tHead = table.getElementsByTagName('thead')[0];
81 if (table.tHead.rows.length != 1)
82 return; // can't cope with two header rows
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).
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];
95 if (table.tFoot == null) {
96 // table doesn't have a tfoot. Create one.
97 tfo = document.createElement('tfoot');
98 table.appendChild(tfo);
100 for (var i = 0; i < sortbottomrows.length; i++) {
101 tfo.appendChild(sortbottomrows[i]);
103 delete sortbottomrows;
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/);
115 if (mtch && typeof sorttable["sort_" + override] == 'function') {
116 headrow[i].sorttable_sortfunction = sorttable["sort_" + override];
118 headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);
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) {
123 sortrevind = document.createElement('span');
124 sortrevind.id = "sorttable_sortrevind";
125 sortrevind.innerHTML = sorttable.icon_down;
126 headrow[i].appendChild(sortrevind);
129 if (headrow[i].className.search(/\bsorttable_sorted\b/) != -1 && headrow[i].innerHTML.search(/\bsorttable_sortfwdind\b/)==-1) {
131 sortfwdind = document.createElement('span');
132 sortfwdind.id = "sorttable_sortfwdind";
133 sortfwdind.innerHTML = sorttable.icon_up;
134 headrow[i].appendChild(sortfwdind);
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) {
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 ? ' <font face="webdings">5</font>' : ' ▴';
152 sortrevind.innerHTML = sorttable.icon_down;
153 this.appendChild(sortrevind);
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',
162 this.removeChild(document.getElementById('sorttable_sortrevind'));
163 sortfwdind = document.createElement('span');
164 sortfwdind.id = "sorttable_sortfwdind";
165// sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
166 sortfwdind.innerHTML = sorttable.icon_up;
167 this.appendChild(sortfwdind);
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', '');
179 sortfwdind = document.getElementById('sorttable_sortfwdind');
181 sortfwdind.parentNode.removeChild(sortfwdind);
183 sortrevind = document.getElementById('sorttable_sortrevind');
185 sortrevind.parentNode.removeChild(sortrevind);
188 this.className += ' sorttable_sorted';
189 sortfwdind = document.createElement('span');
190 sortfwdind.id = "sorttable_sortfwdind";
191// sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
192 sortfwdind.innerHTML = sorttable.icon_up;
193 this.appendChild(sortfwdind);
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
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]];
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);
210 tb = this.sorttable_tbody;
211 for (var j = 0; j < row_array.length; j++) {
212 tb.appendChild(row_array[j][1]);
215 // Highlight odd and even rows properly
216 sorttable.highlight_body(table);
222 * alternate properly the rows of the table,
223 * @param {DOMNode} p_table sorted table
225 highlight_body:function(p_table) {
226 var nb_row=p_table.rows;
228 for (e=1;e<nb_row.length;e++) {
230 if ( nb_row[e].className=="odd" ) nb_row[e].className="even";
232 if ( nb_row[e].className=="even" ) nb_row[e].className="odd";
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]);
242 if (text.match(/^-?[�$�]?[\d,.]+%?$/)) {
243 return sorttable.sort_numeric;
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)
251 first = parseInt(possdate[1]);
252 second = parseInt(possdate[2]);
255 return sorttable.sort_ddmm;
256 } else if (second > 12) {
257 return sorttable.sort_mmdd;
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;
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.
278 hasInputs = (typeof node.getElementsByTagName == 'function') &&
279 node.getElementsByTagName('input').length;
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, '');
290 switch (node.nodeType) {
292 if (node.nodeName.toLowerCase() == 'input') {
293 return node.value.replace(/^\s+|\s+$/g, '');
296 return node.nodeValue.replace(/^\s+|\s+$/g, '');
301 for (var i = 0; i < node.childNodes.length; i++) {
302 innerText += sorttable.getInnerText(node.childNodes[i]);
304 return innerText.replace(/^\s+|\s+$/g, '');
311 reverse: function (tbody) {
312 // reverse the rows in a tbody
314 for (var i = 0; i < tbody.rows.length; i++) {
315 newrows[newrows.length] = tbody.rows[i];
317 for (var i = newrows.length - 1; i >= 0; i--) {
318 tbody.appendChild(newrows[i]);
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, ''));
329 var bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));
334 sort_alpha: function (a, b) {
341 sort_ddmm: function (a, b) {
342 mtch = a[0].match(sorttable.DATE_RE);
351 mtch = b[0].match(sorttable.DATE_RE);
366 sort_mmdd: function (a, b) {
367 mtch = a[0].match(sorttable.DATE_RE);
376 mtch = b[0].match(sorttable.DATE_RE);
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
396 var t = list.length - 1;
401 for (var i = b; i < t; ++i) {
402 if (comp_func(list[i], list[i + 1]) > 0) {
404 list[i] = list[i + 1];
414 for (var i = t; i > b; --i) {
415 if (comp_func(list[i], list[i - 1]) < 0) {
417 list[i] = list[i - 1];
428/* ******************************************************************
429 Supporting functions: bundled here to avoid depending on a library
430 ****************************************************************** */
432// Dean Edwards/Matthias Miller/John Resig
434/* for Mozilla/Opera9 */
435if (document.addEventListener) {
436 document.addEventListener("DOMContentLoaded", sorttable.init, false);
439/* for Internet Explorer */
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
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
460/* for other browsers */
461// Moved into noalyss_script.js
462//window.onload = sorttable.init;
464// written by Dean Edwards, 2005
465// with input from Tino Zijdel, Matthias Miller, Diego Perini
467// http://dean.edwards.name/weblog/2005/10/add-event/
469function dean_addEvent(element, type, handler) {
470 if (element.addEventListener) {
471 element.addEventListener(type, handler, false);
473 // assign each event handler a unique ID
475 handler.$$guid = dean_addEvent.guid++;
476 // create a hash table of event types for the element
479 // create a hash table of event handlers for each element/event pair
480 var handlers = element.events[type];
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];
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;
495// a counter used to create unique IDs
496dean_addEvent.guid = 1;
498function removeEvent(element, type, handler) {
499 if (element.removeEventListener) {
500 element.removeEventListener(type, handler, false);
502 // delete the event handler from the hash table
503 if (element.events && element.events[type]) {
504 delete element.events[type][handler.$$guid];
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) {
527function fixEvent(event) {
528 // add W3C standard event methods
529 event.preventDefault = fixEvent.preventDefault;
530 event.stopPropagation = fixEvent.stopPropagation;
534fixEvent.preventDefault = function () {
535 this.returnValue = false;
537fixEvent.stopPropagation = function () {
538 this.cancelBubble = true;
541// Dean's forEach: http://dean.edwards.name/base/forEach.js
544 Copyright 2006, Dean Edwards
545 License: http://www.opensource.org/licenses/mit-license.php
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);
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);
566// character enumeration
567String.forEach = function (string, block, context) {
568 Array.forEach(string.split(""), function (chr, index) {
569 block.call(context, chr, index, string);
573// globally resolve forEach enumeration
574var forEach = function (object, block, context) {
576 var resolve = Object; // default
577 if (object instanceof Function) {
578 // functions have a "length" property
580 } else if (object.forEach instanceof Function) {
581 // the object implements a custom forEach method so use that
582 object.forEach(block, context);
584 } else if (typeof object == "string") {
585 // the object is a string
587 } else if (typeof object.length == "number") {
588 // the object is array-like
591 resolve.forEach(object, block, context);