JSFiddle - React, Tailwind, and code Playground

by patbuchanan

HTML

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js"></script>
In this example you can specifiy exactly which div to sync with.<br><br>

<div ng-app="myApp">
    <div id="topGrid" sync-horizontal-scroll-with="summaryGrid">
        <div class="content">Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid Top grid</div>
    </div>
    <div id="summaryGrid">
        <div class="content">Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid Bottom grid</div>
    </div>
</div>

<br>Note that the top div's scrollbar is hidden.  This is useful for things like stacked datagrids that need to appear as one, but still scroll together.

CSS

#topGrid {
    background: yellow;
    height: 100px;
    overflow-x: auto;
}
#summaryGrid {
    background: red;
    height: 100px;
    overflow-x: auto;
}
.content{
    width: 300%;
    height: 100%;
}

JavaScript

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

myApp.directive('syncHorizontalScrollWith', ['$timeout', function ($timeout) {
    console.log('before');
    var result = {
        restrict: 'A',
        scope: {},
        link: function (scope, element, attributes) {
            $timeout(function () {
                var dSource = $('#' + attributes.syncHorizontalScrollWith);
                var dTarget = element;
                console.log('here!');
                dTarget.css('overflow-x', 'hidden');

                dSource.on('scroll', function () {
                    $(dTarget).scrollLeft(dSource.scrollLeft());
                });
            })
        }
    };

    return result;
}]);