sync slide of scrollbars of different sizes

Asked

Viewed 21 times

-2

someone has some insight on how to synchronize the finish of two existing scrollbars of different sizes on separate Ivs?

<div id="div1" style="float:left;overflow:auto;height:400px;width:200px;">
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

<div id="div2" style="float:right;overflow:auto;height:300px;width:200px;">
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
        $("#div1").scroll(function () { 
  $("#div2").scrollTop($("#div1").scrollTop());
  $("#div2").scrollLeft($("#div1").scrollLeft());
});
$("#div2").scroll(function () { 
  $("#div1").scrollTop($("#div2").scrollTop());
  $("#div1").scrollLeft($("#div2").scrollLeft());
});
</script>

1 answer

0

With the scrollHeight attribute we can get the scroll percentage and use this value to set the position in the other div.

$("#div1").scroll(function () {
    var scrollPercentage = Math.round(100 * $("#div1").scrollTop() / ($("#div1").prop('scrollHeight') - $("#div1").height()));
    var scroll = Math.round(scrollPercentage * ($("#div2").prop('scrollHeight') - $("#div2").height()) / 100);
    $("#div2").scrollTop(scroll);
    $("#div2").scrollLeft($("#div1").scrollLeft());
});
$("#div2").scroll(function () {
    var scrollPercentage = Math.round(100 * $("#div2").scrollTop() / ($("#div2").prop('scrollHeight') - $("#div2").height()));
    var scroll = Math.round(scrollPercentage * ($("#div1").prop('scrollHeight') - $("#div1").height()) / 100);
    $("#div1").scrollTop(scroll);
    $("#div1").scrollLeft($("#div2").scrollLeft());
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.