* Sort the rows in a HTML Table * * @param Table The Table DOM object * @param col The zero-based column number by which to sort * @param dir Optional. The sort direction; pass 1 for asc; -1 for desc * @returns void
(Table, col, dir)
| 19 | * @returns void |
| 20 | */ |
| 21 | function sortTable(Table, col, dir) { |
| 22 | var sortClass, i; |
| 23 | |
| 24 | // get previous sort column |
| 25 | sortTable.sortCol = -1; |
| 26 | sortClass = Table.className.match(/js-sort-\d+/); |
| 27 | if (null != sortClass) { |
| 28 | sortTable.sortCol = sortClass[0].replace(/js-sort-/, ''); |
| 29 | Table.className = Table.className.replace(new RegExp(' ?' + sortClass[0] + '\\b'), ''); |
| 30 | } |
| 31 | // If sort column was not passed, use previous |
| 32 | if ('undefined' === typeof col) { |
| 33 | col = sortTable.sortCol; |
| 34 | } |
| 35 | |
| 36 | if ('undefined' !== typeof dir) { |
| 37 | // Accept -1 or 'desc' for descending. All else is ascending |
| 38 | sortTable.sortDir = dir == -1 || dir == 'desc' ? -1 : 1; |
| 39 | } else { |
| 40 | // sort direction was not passed, use opposite of previous |
| 41 | sortClass = Table.className.match(/js-sort-(a|de)sc/); |
| 42 | if (null != sortClass && sortTable.sortCol == col) { |
| 43 | sortTable.sortDir = 'js-sort-asc' == sortClass[0] ? -1 : 1; |
| 44 | } else { |
| 45 | sortTable.sortDir = 1; |
| 46 | } |
| 47 | } |
| 48 | Table.className = Table.className.replace(/ ?js-sort-(a|de)sc/g, ''); |
| 49 | |
| 50 | // update sort column |
| 51 | Table.className += ' js-sort-' + col; |
| 52 | sortTable.sortCol = col; |
| 53 | |
| 54 | // update sort direction |
| 55 | Table.className += ' js-sort-' + (sortTable.sortDir == -1 ? 'desc' : 'asc'); |
| 56 | |
| 57 | // get sort type |
| 58 | if (col < Table.tHead.rows[Table.tHead.rows.length - 1].cells.length) { |
| 59 | sortClass = Table.tHead.rows[Table.tHead.rows.length - 1].cells[col].className.match(/js-sort-[-\w]+/); |
| 60 | } |
| 61 | // Improved support for colspan'd headers |
| 62 | for (i = 0; i < Table.tHead.rows[Table.tHead.rows.length - 1].cells.length; i++) { |
| 63 | if (col == Table.tHead.rows[Table.tHead.rows.length - 1].cells[i].getAttribute('data-js-sort-colNum')) { |
| 64 | sortClass = Table.tHead.rows[Table.tHead.rows.length - 1].cells[i].className.match(/js-sort-[-\w]+/); |
| 65 | } |
| 66 | } |
| 67 | if (null != sortClass) { |
| 68 | sortTable.sortFunc = sortClass[0].replace(/js-sort-/, ''); |
| 69 | } else { |
| 70 | sortTable.sortFunc = 'string'; |
| 71 | } |
| 72 | // Set the headers for the active column to have the decorative class |
| 73 | Table.querySelectorAll('.js-sort-active').forEach(function(Node) { |
| 74 | Node.className = Node.className.replace(/ ?js-sort-active\b/, ''); |
| 75 | }); |
| 76 | Table.querySelectorAll('[data-js-sort-colNum="' + col + '"]:not(:empty)').forEach(function(Node) { |
| 77 | Node.className += ' js-sort-active'; |
| 78 | }); |