Fixed scrolling table header

Makes it easier to read long tables by displaying a fixed header when the heading row goes out of view as a result of scrolling.

by Leolloyd Andrade

HTML

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

<p style="margin:30px 0;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>

<div class="page-title">
  <strong>Title</strong>
  <div class="fixed-bar">
    <ul class="fixed-bar__tb">
      <li>5 rows selected.</li>
      <li><a href="#"><i class="material-icons md-18">bookmark</i></a></li>
      <li><a href="#"><i class="material-icons md-18">backup</i></a></li>
      <li><a href="#"><i class="material-icons md-18">autorenew</i></a></li>
    </ul>
  </div>
</div>

<div class="tbl-resp">
  <table id="tbl1" class="tbl-resp__tbl">
     <thead>
      <tr>
        <th>col 1</th>
        <th>col 2 col 2 col 2</th>
        <th>col 3</th>
        <th>col 4</th>
        <th>col 5</th>
        <th>col 6</th>
        <th>col 7</th>
        <th>col 8</th>
        <th>col 9</th>
        <th>col 10</th>
        <th>col 11</th>
        <th>col 12</th>
      </tr>
    </thead> 
  </table>
</div>

<p style="margin:30px 0;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>

<div class="tbl-resp">
  <table id="tbl2" class="tbl-resp__tbl">
     <thead>
      <tr>
        <th>col 1</th>
        <th>col...

SCSS

body {
  padding-left:20px;
  padding-right:20px;
  padding-bottom:300px;
}

.page-title {
  position:relative;
  margin-bottom:20px;
}


.fixed-bar {
  right:0;
  top:0px;
  position:absolute;

  &__tb {
    list-style:none;
    
    > li {
      display:inline-block;

      > a {
        width:30px;
        height:30px;
        display:inline-block;
        text-align:center;
        color: #adadad;

        &:hover,
        &:active,
        &:focus {
          color:#000;
        }
      } // .fixed-bar__tb > li > a
    } // .fixed-bar__tb > li
  } // .fixed-bar__tb
} // .fixed-bar

.tbl-resp {
  width:100%;  
  border: 1px solid red;
  overflow-x: auto;

  &__tbl {
    border: 0;
    border-collapse:collapse;
    
    > thead,
    > tbody,
    > tfoot {
      > tr {
        > th,
        > td {
          border: 1px solid #ddd;
          line-height: 1.428571429;
          padding: 5px;
          vertical-align: top;
          white-space: nowrap;
        }
      }
    }
  } // .tbl-resp__tbl
  
  &__fixed-hdr {
    background-color: white; 
    border-bottom: 1px solid blue;
    display:none;
    overflow: hidden;
    position: fixed;
    top: 0;
    white-space: nowrap;
  } // .tbl-resp__fixed-hdr
  
  &__tb {
    background-color:#eee;
    min-height:40px;
    height:40px;
  }
  
  &__col {
    border-right:1px solid #ddd;
    display: inline-block;
    padding: 3px;
    vertical-align:middle;
    white-space:normal;
  } // .tbl-resp__col  
} // .tbl-resp

JavaScript

/* globals $ */
$(function() {
  /**
   * NOTE: Table element must have an id like so: '<table id="tbl1">'.
   */

  var _ticking = false,
    _lastScrollTop = 0,
    _lastScrollLeft = 0,
    _$tbl,
    _bounds = [];
    
  function addDummyRows(id, rows, cols) {
  	var $tbody = $('<tbody></tbody>');
  	for (var i = 1; i <= rows; i++) {
    	var $tr = $('<tr></tr>');
      for (var j = 1; j <= cols; j++) {
      	$tr.append('<td>cell ' + i + ':' + j + '</td>');
      }
      $tbody.append($tr);
    }
    $(id).append($tbody);
  }
  
  function throttledScroll(e) {
    if (e.currentTarget === window) {
      _lastScrollTop = $(this).scrollTop();
      _$tbl = null;
    } else {
      _$tbl = $(this);
      _lastScrollLeft = _$tbl.scrollLeft();
    }
    
    if (!_ticking) {
      window.requestAnimationFrame(function() {
        rAF(_lastScrollLeft, _lastScrollTop, _$tbl);
        _ticking = false;
      });
    }
    _ticking = true;
  }
	
	function wireupScroll() {
  	$(window).scroll(throttledScroll);
    $('.tbl-resp').scroll(throttledScroll);
  }
	
  function rAF(scrollLeft, scrollTop, $tbl) {
  	var toolbar;
  
  	if ($tbl) { 
    	// horizontal scroll
      var offsetLeft = 0 - scrollLeft;
      $tbl.find('.tbl-resp__col').first().css('margin-left', offsetLeft);
    } else {
    	// vertical scroll
      for (var i = 0; i < _bounds.length; i++) {
      	var tbl = _bounds[i];
        var $hdr = $('#' + tbl.id).prev('.tbl-resp__fixed-hdr');
        if (tbl.top < scrollTop && (tbl.bottom - 25) > scrollTop) {
        	if (!tbl.showing) {
            toolbar = $hdr.closest('.tbl-resp').prev('.page-title').children('.fixed-bar')[0];
            $hdr.append(toolbar);
            $hdr.show();
            tbl.showing = true;
          }
        } else {
        	if (tbl.showing) {
            $hdr.hide();
          	toolbar = $hdr.children('.fixed-bar')[0];
            $hdr.closest('.tbl-resp').prev('.page-title').append(toolbar);
            tbl.showing = false;
 ...