Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize scroll between two elements with different height

I have two DIV elements #page and #block :

<div id="page"></div>
<div id="block"></div>

#block element has fixed position and long content inside with overflow:hidden property.

#page element has some content inside too, but it height of #page will be longer or shorter then #block height.

My goal is to achieve synchronized scroll between this two elements. Something like this:

enter image description here

I need to calculate speed of #block element scroll, because header and footer elements of #page and #block should be at same position from beginning and at the end of scroll.

The way I tried to achieve this:

  • Calculated height of #page element
  • Calculated height of #block element content (because block element is fixed and has alwas fixed height)
  • Calculated #block element scroll speed by:

    $("#block").outerHeight / $("#page").outerHeight

  • Triggered .scrollTop() of #block

It's working from the beginning and #block element scroll is faster then #page element scroll, but at the end, #block is not scrolled fully.

Here is my JsFiddle: http://jsfiddle.net/zur4ik/bQYrf/2/

Maybe anyone can see what I'm doing wrong?

Thanks in advance.

like image 434
zur4ik Avatar asked Nov 05 '13 09:11

zur4ik


2 Answers

You must take the window height into the case and subtract it from the elements heights.

$(window).scroll(function() {
    var pageH = $('#page').height() - $(this).height();
    var pageT = this.scrollY - $('#page').offset().top;

    $('#block').scrollTop(pageT / pageH * ($('#blockLength').height() - $(this).height()));
});

Here's the updated fiddle: http://jsfiddle.net/bQYrf/4/

like image 89
matewka Avatar answered Oct 31 '22 19:10

matewka


I have found two examples of this same question already answered in SO:

If I understand you question correctly this is exactly what you are looking for: Synchronized scrolling using jQuery?

This is also a good solution: How do I synchronize the scroll position of two divs?

like image 45
usefulcat Avatar answered Oct 31 '22 19:10

usefulcat