DIV activating scroll in another DIV even with different sizes

8

I have two div of the same height, but with different contents. And when I do the scroll in one, I wanted the other to go in the same (or at least close to the same) position.

The problem is that their contents do not have the same size , and consequently the size of the scroll bar ends up being different between them. But even with the difference in size I would like to make the second scroll accompany the first one, so that if I roll until the end of the first div the second should also go to the end, / p>

I do not know if I could make myself clear, but here follows an example of what I intend to do .

(function () {
    var target = $("#target")[0]; // <== Getting raw element
    $("#source").scroll(function () {
        target.scrollTop = this.scrollTop;
        target.scrollLeft = this.scrollLeft;
    });
})();

I used a solution found in this answer , but the problem is just that the scroll of the second only goes as far as the first one ends, that is, it does not behave properly.

Is there any way to create an "intelligent" scroll-mirror?

    
asked by anonymous 07.05.2014 / 18:29

1 answer

5

An approximate idea would be to use percentages. First you need to know how many px scroll source has moved down, so we do the following rule of 3:

scrollTopSource = x
(scrollHeigthSource - clientHeigthSource) = 100
x = 100 * scrollTopSource / (scrollHeigthSource - clientHeigthSource)

Then we have to convert this percentage to px into target , for this we use the following rule 3:

scrollTopTarget = x
(scrollHeigthTarget - clientHeigthTarget) = 100
scrollTopTarget = (scrollHeigthTarget - clientHeigthTarget) * x / 100

In the code, just replace the following

target.scrollTop = 100 * this.scrollTop / this.scrollTop;
target.scrollLeft = 100 * this.scrollLeft / this.scrollWidth;

by the following lines:

target.scrollTop = (target.scrollHeight-this.clientHeight) * (100 * this.scrollTop / (this.scrollHeight-this.clientHeight)) / 100;
target.scrollLeft = (target.scrollWidth-this.clientWidth) * (100 * this.scrollLeft / (this.scrollWidth-this.clientWidth)) / 100;

As can be seen in this jsfiddle , it needs some adjustment to correct rounding problems when the scroll bar comes to the end.

    
07.05.2014 / 19:09