Search code examples
javascriptjquery

How do I synchronize the scroll position of two divs?


I want to have 2 divs sized to a particular width (i.e. 500px). One above the other aligned horizontally.

The top box should hide its scroll bar, the bottom should show a scroll bar and when the user scrolls I'd like the offset of the top box to change to the value of the bottom box. So that when the bottom DIV scrolls horizontally it appears that the top DIV is also scrolling in unison.

I'm happy to do this in Jquery if it makes the process easier.


Solution

  • $('#bottom').on('scroll', function () {
        $('#top').scrollTop($(this).scrollTop());
    });
    

    Here we are using .scrollTop() for all it's worth, getting the scrollTop value from the element with scroll-bars, and setting the scrollTop for the other element to sync their scroll positions: http://api.jquery.com/scrollTop

    This assumes that your bottom element has an ID of bottom and your top element has an ID of top.

    You can hide the scroll-bars for the top element using CSS:

    #top {
        overflow : hidden;
    }
    

    Here is a demo: http://jsfiddle.net/sgcer/1884/

    I suppose I've never really had a reason to do this, but it looks pretty cool in action.