Pouknouki

JavaScript Table Sorter

Jun 19th, 2013
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   <script>
  2.         (function(document) {
  3.         'use strict';
  4.  
  5.         var LightTableSorter = (function(Arr) {
  6.  
  7.             var _th, _cellIndex, _order = '';
  8.  
  9.             function _text(row) {
  10.                 return row.cells.item(_cellIndex).textContent.toLowerCase();
  11.             }
  12.  
  13.             function _sort(a, b) {
  14.                 var va = _text(a), vb = _text(b), n = parseInt(va, 10);
  15.                 if (n) {
  16.                     va = n;
  17.                     vb = parseInt(vb, 10);
  18.                 }
  19.                 return va > vb ? 1 : va < vb ? -1 : 0;
  20.             }
  21.  
  22.             function _toggle() {
  23.                 var c = _order !== 'asc' ? 'asc' : 'desc';
  24.                 _th.className = (_th.className.replace(_order, '') + ' ' + c).trim();
  25.                 _order = c;
  26.             }
  27.  
  28.             function _reset() {
  29.                 _th.className = _th.className.replace('asc', '').replace('desc', '');
  30.                 _order = '';
  31.             }
  32.  
  33.             function onClickEvent(e) {
  34.                 if (_th && _cellIndex !== e.target.cellIndex) {
  35.                     _reset();
  36.                 }
  37.                 _th = e.target;
  38.                 _cellIndex = _th.cellIndex;
  39.                 //var tbody = _th.offsetParent.getElementsByTagName('tbody')[0],
  40.                 var tbody = _th.offsetParent.getElementsById('body2')[0],
  41.                     rows = tbody.rows;
  42.                 if (rows) {
  43.                     rows = Arr.sort.call(Arr.slice.call(rows, 0), _sort);
  44.                     if (_order === 'asc') {
  45.                         Arr.reverse.call(rows);
  46.                     }
  47.                     _toggle();
  48.                     tbody.innerHtml = '';
  49.                     Arr.forEach.call(rows, function(row) { tbody.appendChild(row); });
  50.                 }
  51.             }
  52.  
  53.             return {
  54.                 init: function() {
  55.                     var ths = document.getElementsByTagName('th');
  56.                     Arr.forEach.call(ths, function(th) { th.onclick = onClickEvent; });
  57.                 }
  58.             };
  59.         })(Array.prototype);
  60.  
  61.         document.addEventListener('readystatechange', function() {
  62.             if (document.readyState === 'complete') {
  63.                 LightTableSorter.init();
  64.             }
  65.         });
  66.  
  67.         })(document);
  68.     </script>
Advertisement
Add Comment
Please, Sign In to add comment