1

I'm trying to sync the scrolling behaviour of 2 divs.

Example:
This site has exactly what I'm trying to do (at the bottom, the left and right side sync as you scroll).

My Attempt:
I found this Fiddle which is kinda what I'm trying to do. I tried starting with this code and couldn't get anywhere. Here's the code:

var $divs = $('#div1, #div2');
var sync = function(e){
    var $other = $divs.not(this).off('scroll'), other = $other.get(0);
    var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
    other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
    setTimeout( function(){ $other.on('scroll', sync ); },10);
}
$divs.on( 'scroll', sync);

This seems like a good approach for when you have two side-by-side divs that are uneven heights. Would be a cool jQuery plugin to build.

My Fiddle here.

EDIT 1:

I was able to unminify and find a part of the code from the first example link that I assume handles this, you can see that part of the code here: https://gist.github.com/tenold/f6b77984c27d0bde99c2

EDIT 2:

I was able to get the above code working, but it's still pretty messy. http://jsfiddle.net/tenold/xquLevc0/6/

Corey
  • 2,453
  • 4
  • 35
  • 63
  • So you're asking for us to help you get them to sync up so that when you scroll halfway down the right column you're halfway down the left? I'm just clarifying – zfrisch Jun 09 '15 at 00:07
  • Yes, so as you see in the first link, when you get to the bottom, the tops of the divs are even. The right column is way shorter than the left column, so when you scroll it scrolls slower so that when you get to the bottom the bottoms of the divs are matched evenly. – Corey Jun 09 '15 at 00:09

1 Answers1

2

Looks like you want to use
element.scrollTop / (element.scrollHeight - element.offsetHeight)
to have a common percentage to scroll.

You'll want to set up loops like what you already have, or alternatively, periodically set the scrollTop value, like in this answer.

Hope that helps!

Community
  • 1
  • 1
Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20