Search code examples
javascriptjqueryhandsontable

Link Scrolling Between Two Tables


I have two same-sized tables on the same page. How can I link the scrolling between them so that when I scroll to the right at the top it also scrolls to the right at the bottom etc?

http://plnkr.co/edit/tXpr9hRGTDUEnrjEwr7w

<div class="scroll-left">
  <div id="example1"></div>
</div>
<div class="scroll-right">
  <div id="example2"></div>
</div>

document.addEventListener("DOMContentLoaded", function() {

function getData() {
  var data = [
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [1,2,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0],[1,2,3,4,5,6,7,8,9,0],[0,0,0,0,0,0,0,0,0,0]
  ];
  return data;
}

var example1 = document.getElementById('example1');
var example2 = document.getElementById('example2');

var hot1 = new Handsontable(example1, {
  data: getData(),
  rowHeaders: true,
  colHeaders: true,
});

var hot2 = new Handsontable(example2, {
  data: getData(),
  rowHeaders: true,
  colHeaders: true,
});



});

Solution

  • You can add this code to the end of yours to link the scrolling from the top table to the bottom table:

    var $eg1holder = $(example1).find('.wtHolder');
    var $eg2holder = $(example2).find('.wtHolder');
    
    $eg1holder.scroll(function() {
      var x = $(this).scrollTop();
      var y = $(this).scrollLeft();
      $eg2holder.scrollTop(x).scrollLeft(y);
    });
    

    http://plnkr.co/edit/vCn8Fru5SWTT6Sn99p33