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">
26 ....<span id="sorttable_sortfwdind"> ▾</span>
29 <td sorttable_customkey="<?=$row_bank['b_date']?>"> // format YYYYMMDD
31 force as numeric (normally useless):
32 <th class="sorttable_numeric">Part number</th>
34 Column to ignore : <th class="sorttable_nosort">
35 To avoid the sort on the last row, use tfoot
40var stIsIE = /*@cc_on!@*/false;
44 // quit if this function has already been called
45 if (arguments.callee.done)
47 // flag this function so we don't do the same thing twice
48 arguments.callee.done = true;
51 clearInterval(_timer);
53 if (!document.createElement || !document.getElementsByTagName)
56 sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
58 forEach(document.getElementsByTagName('table'), function (table) {
59 if (table.className.search(/\bsortable\b/) != -1) {
60 sorttable.makeSortable(table);
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);
73 // Safari doesn't support table.tHead, sigh
74 if (table.tHead == null)
75 table.tHead = table.getElementsByTagName('thead')[0];
77 if (table.tHead.rows.length != 1)
78 return; // can't cope with two header rows
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).
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];
91 if (table.tFoot == null) {
92 // table doesn't have a tfoot. Create one.
93 tfo = document.createElement('tfoot');
94 table.appendChild(tfo);
96 for (var i = 0; i < sortbottomrows.length; i++) {
97 tfo.appendChild(sortbottomrows[i]);
99 delete sortbottomrows;
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/);
111 if (mtch && typeof sorttable["sort_" + override] == 'function') {
112 headrow[i].sorttable_sortfunction = sorttable["sort_" + override];
114 headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);
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
120 // existence flag for span
122 if ( headrow[i].hasChildNodes())
124 var children=headrow.childNodes;
125 for (var x = 0;x < children.length;x++)
127 if (headrow[i].children[x].id=='sorttable_sortrevind') {
132 // if we're already sorted by this column,
134 sortrevind = document.createElement('span');
135 sortrevind.id = "sorttable_sortrevind";
136 sortrevind.innerHTML = '<img src="image/down.gif">';
137 headrow[i].appendChild(sortrevind);
141 if (headrow[i].className.search(/\bsorttable_sorted\b/) != -1) {
142 // existence flag for span
144 // if in headrow[i] the span doesn't exist , then add it
145 if ( headrow[i].hasChildNodes())
147 var children=headrow.childNodes;
148 for (var x = 0;x < children.length;x++)
150 if (headrow[i].children[x].id=='sorttable_sortfwdind') {
155 // if we're already sorted by this column,
157 sortfwdind = document.createElement('span');
158 sortfwdind.id = "sorttable_sortfwdind";
159 sortfwdind.innerHTML = '<img src="image/up.gif">';
160 headrow[i].appendChild(sortfwdind);
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) {
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 ? ' <font face="webdings">5</font>' : ' ▴';
178 sortrevind.innerHTML = '<img src="image/down.gif">';
179 this.appendChild(sortrevind);
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',
188 this.removeChild(document.getElementById('sorttable_sortrevind'));
189 sortfwdind = document.createElement('span');
190 sortfwdind.id = "sorttable_sortfwdind";
191// sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
192 sortfwdind.innerHTML = '<img src="image/up.gif">';
193 this.appendChild(sortfwdind);
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', '');
205 sortfwdind = document.getElementById('sorttable_sortfwdind');
207 sortfwdind.parentNode.removeChild(sortfwdind);
209 sortrevind = document.getElementById('sorttable_sortrevind');
211 sortrevind.parentNode.removeChild(sortrevind);
214 this.className += ' sorttable_sorted';
215 sortfwdind = document.createElement('span');
216 sortfwdind.id = "sorttable_sortfwdind";
217// sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';
218 sortfwdind.innerHTML = '<img src="image/up.gif">';
219 this.appendChild(sortfwdind);
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
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]];
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);
236 tb = this.sorttable_tbody;
237 for (var j = 0; j < row_array.length; j++) {
238 tb.appendChild(row_array[j][1]);
241 // Highlight odd and even rows properly
242 sorttable.highlight_body(table);
248 * alternate properly the rows of the table,
249 * @param {DOMNode} p_table sorted table
251 highlight_body:function(p_table) {
252 var nb_row=p_table.rows;
254 for (e=1;e<nb_row.length;e++) {
256 if ( nb_row[e].className=="odd" ) nb_row[e].className="even";
258 if ( nb_row[e].className=="even" ) nb_row[e].className="odd";
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]);
268 if (text.match(/^-?[�$�]?[\d,.]+%?$/)) {
269 return sorttable.sort_numeric;
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)
277 first = parseInt(possdate[1]);
278 second = parseInt(possdate[2]);
281 return sorttable.sort_ddmm;
282 } else if (second > 12) {
283 return sorttable.sort_mmdd;
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;
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.
304 hasInputs = (typeof node.getElementsByTagName == 'function') &&
305 node.getElementsByTagName('input').length;
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, '');
316 switch (node.nodeType) {
318 if (node.nodeName.toLowerCase() == 'input') {
319 return node.value.replace(/^\s+|\s+$/g, '');
322 return node.nodeValue.replace(/^\s+|\s+$/g, '');
327 for (var i = 0; i < node.childNodes.length; i++) {
328 innerText += sorttable.getInnerText(node.childNodes[i]);
330 return innerText.replace(/^\s+|\s+$/g, '');
337 reverse: function (tbody) {
338 // reverse the rows in a tbody
340 for (var i = 0; i < tbody.rows.length; i++) {
341 newrows[newrows.length] = tbody.rows[i];
343 for (var i = newrows.length - 1; i >= 0; i--) {
344 tbody.appendChild(newrows[i]);
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, ''));
355 var bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));
360 sort_alpha: function (a, b) {
367 sort_ddmm: function (a, b) {
368 mtch = a[0].match(sorttable.DATE_RE);
377 mtch = b[0].match(sorttable.DATE_RE);
392 sort_mmdd: function (a, b) {
393 mtch = a[0].match(sorttable.DATE_RE);
402 mtch = b[0].match(sorttable.DATE_RE);
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
422 var t = list.length - 1;
427 for (var i = b; i < t; ++i) {
428 if (comp_func(list[i], list[i + 1]) > 0) {
430 list[i] = list[i + 1];
440 for (var i = t; i > b; --i) {
441 if (comp_func(list[i], list[i - 1]) < 0) {
443 list[i] = list[i - 1];
454/* ******************************************************************
455 Supporting functions: bundled here to avoid depending on a library
456 ****************************************************************** */
458// Dean Edwards/Matthias Miller/John Resig
460/* for Mozilla/Opera9 */
461if (document.addEventListener) {
462 document.addEventListener("DOMContentLoaded", sorttable.init, false);
465/* for Internet Explorer */
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
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
486/* for other browsers */
487// Moved into scripts.js
488//window.onload = sorttable.init;
490// written by Dean Edwards, 2005
491// with input from Tino Zijdel, Matthias Miller, Diego Perini
493// http://dean.edwards.name/weblog/2005/10/add-event/
495function dean_addEvent(element, type, handler) {
496 if (element.addEventListener) {
497 element.addEventListener(type, handler, false);
499 // assign each event handler a unique ID
501 handler.$$guid = dean_addEvent.guid++;
502 // create a hash table of event types for the element
505 // create a hash table of event handlers for each element/event pair
506 var handlers = element.events[type];
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];
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;
521// a counter used to create unique IDs
522dean_addEvent.guid = 1;
524function removeEvent(element, type, handler) {
525 if (element.removeEventListener) {
526 element.removeEventListener(type, handler, false);
528 // delete the event handler from the hash table
529 if (element.events && element.events[type]) {
530 delete element.events[type][handler.$$guid];
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) {
553function fixEvent(event) {
554 // add W3C standard event methods
555 event.preventDefault = fixEvent.preventDefault;
556 event.stopPropagation = fixEvent.stopPropagation;
560fixEvent.preventDefault = function () {
561 this.returnValue = false;
563fixEvent.stopPropagation = function () {
564 this.cancelBubble = true;
567// Dean's forEach: http://dean.edwards.name/base/forEach.js
570 Copyright 2006, Dean Edwards
571 License: http://www.opensource.org/licenses/mit-license.php
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);
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);
592// character enumeration
593String.forEach = function (string, block, context) {
594 Array.forEach(string.split(""), function (chr, index) {
595 block.call(context, chr, index, string);
599// globally resolve forEach enumeration
600var forEach = function (object, block, context) {
602 var resolve = Object; // default
603 if (object instanceof Function) {
604 // functions have a "length" property
606 } else if (object.forEach instanceof Function) {
607 // the object implements a custom forEach method so use that
608 object.forEach(block, context);
610 } else if (typeof object == "string") {
611 // the object is a string
613 } else if (typeof object.length == "number") {
614 // the object is array-like
617 resolve.forEach(object, block, context);