How to realize two divs scrolling synchronously with one scrollbar

created at 09-28-2021 views: 2

html

<div id="div1">
    // code...
</div>
<div id="div2">
    // code...
</div>

At the beginning I thought that the scroll of two divs should modify the scrollTop of the other div at the same time, but this will cause a freeze, and the scrolling is very slow. This is caused by mutual calls.
as follows:

  $("#div1").scroll(function(){
      $("#div2").scrollTop($(this).scrollTop()); // vertical scrollbar
      $("#div2").scrollLeft($(this).scrollLeft()); // horizontal scrollbar
  });    
$("#div2").scroll(function(){
      $("#div1").scrollTop($(this).scrollTop()); // vertical scrollbar
      $("#div1").scrollLeft($(this).scrollLeft()); // horizontal scrollbar
  });

solution

Further modification, div1 uses scroll and div2 to monitor mouse wheel events to set the scrollTop of div1
as follows:

$("#div1").scroll(function(){
    $("#div2").scrollTop($(this).scrollTop()); // vertical scrollbar
    $("#div2").scrollLeft($(this).scrollLeft()); // horizontal scrollbar
});    
$("#div2").on("mousewheel DOMMouseScroll", function(e){
    var scroll_top = $("#div1").scrollTop();
    var scroll_left = $("#div1").scrollLeft();
    if(e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0){
        $("#div1").scrollTop(scroll_top - 25);
        $("#div1").scrollLeft(scroll_left - 25)
    } else {
        $("#div1").scrollTop(scroll_top +25);
        $("#div1").scrollLeft(scroll_left +25)
    }
    e.preventDefault()
});
Please log in to leave a comment.