Side-by-side synchronized scrolling

This was surprisingly hard to figure out, although in retrospect it seems really simple. The problem was that I was trying to scroll two elements of different heights, and they kept getting out of synch by the time one reached the bottom.

To back it up, it’s really easy to make an overflow: scroll or overflow: auto element scroll within its container, you just manipulate its scrollTop attribute.

$('foo').observe('scroll', function(evt){
  $('bar').scrollTop = this.scrollTop();
});

So when foo is scrolled with the mouse or anything else that fires the scroll event, bar will match it 1:1. But that’s a naive solution – it will make bar scroll exactly as far as foo has scrolled from the top of its overflowed box – in pixels. If bar is taller or shorter than foo, then you have a mess. What I needed was a proportional scroll observer. So I tried this:

$('foo').observe('scroll', function(evt){
  var ratio = this.scrollHeight / $('bar').scrollHeight;
  $('bar').scrollTop = Math.ceil(this.scrollTop() / ratio);
});

This worked up to a point, but when I got to the bottom of the left box, there was a bunch more content to go on the right.

What I finally realized was that the difference between the scrollTop and the scrollHeight was being thrown off by the objects’ height. They were set to be the same height (to get the side-by-side overflow) but that height was a fixed dimension, and a different proportion from one box to the other in relation to the overall height of the content. This difference was amplified by the calculation as it went along.

Here’s where I ended up:

http://scripty.walterdavisstudio.com/side-by-side.thml

The difference is that I subtracted the height of the box before I calculated the ratio, so the difference does not get compounded. The two elements scroll in perfect synchrony.

Walter


dynamo mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

http://scripty.walterdavisstudio.com/side-by-side.html

On Aug 23, 2014, at 5:38 PM, Walter Lee Davis wrote:

http://scripty.walterdavisstudio.com/side-by-side.thml


dynamo mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options