39113003

Moving to the selected row in the HTML table when the table has scrollbar

by Reid Horton

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
  <div class="scrolling-container">
    <table>
      <tr ng-repeat="k in items">
        <td>{{ k }}</td>
      </tr>
    </table>
  </div>
  <!-- As an example, scroll to the 40th element -->
  <button ng-click="scrollItemIntoView()">
    Scroll to Bottom
  </button>
</div>

CSS

div.scrolling-container {
  height: 200px;
  overflow: scroll;
  background-color: lightgray;
}

JavaScript

var app = angular.module("myApp", []);

app.controller("MainCtrl", function($scope) {

	// Populate the table with 0..100
  $scope.items = [];
  for (var i = 0; i < 100; i++) {
    $scope.items.push(i);
  }

	// This function is called when the button is clicked.
  $scope.scrollItemIntoView = function() {

    var scrollElement = $('.scrolling-container')[0];
    var itemToView = $('tr')[40];
    
    // This is where it all goes down.
    if (!itemIsInViewport(itemToView)) {
      scrollElement.scrollTop = itemToView.offsetTop;
    }

		// Determines if the item is already in view.
    function itemIsInViewport(item) {
      var $scrollElement = $('.scrolling-container');
      var upperBound = item.offsetTop;
      var lowerBound = item.offsetTop - $scrollElement.innerHeight();
      var currentPosition = $scrollElement.scrollTop();
      return lowerBound < currentPosition && currentPosition < upperBound;
    }

  }

});