Synchronized scrolling in Angular 1.5

It's rare, but sometimes you need two independent elements to scroll at the same time. It's not a hard problem to solve using the DOM. Just bind the scroll event of one element to the other and update the scrollLeft (or scrollUp for vertical) property of the other.

The Angular framework frowns upon direct DOM manipulation. It functions a lot better inside of a directive.

angular.module('demoApp', [])  
  .directive('syncScroll', function() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        var scroller = angular.element(document.getElementById(attrs.syncScroll));
        scroller.bind('scroll', function() {
          element[0].scrollLeft = scroller[0].scrollLeft;
        });
      }
    };
});

This directive works by passing an element in as an attribute eg sync-scroll="scroll1", where scroll1 is the id of the element.

Check out the JSFiddle to see it in action.

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA