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.

Answers:

Answer
$('#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.

Answer

I noticed that his question was pretty old, but I thought I could leave a jQuery implementation that works much better than using timers. Here, I am using two event listeners like the previously used solutions but, this will use proportions/percentage to sync scrolls for two differently sized div boxes. You can apply this same knowledge to get the position the scrollbars to a Vanilla JS solution. This will make the scrolling between the two divs much smoother.

/** Scroll sync between editor and preview **/
// Locks so that only one pane is in control of scroll sync
var eScroll = false;
var pScroll = false;
// Set the listener to scroll
this.edit.on('scroll', function() {
    if(eScroll) { // Lock the editor pane
        eScroll = false;
        return;
    }
    pScroll = true; // Enable the preview scroll

    // Set elements to variables
    let current = self.edit.get(0);
    let other = self.preview.get(0);

    // Calculate the position of scroll position based on percentage
    let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);

    // Set the scroll position on the other pane
    other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
});
this.preview.on('scroll', function() {
    if(pScroll) { // Lock the preview pane
        pScroll = false;
        return;
    }
    eScroll = true; // Enable the editor scroll

    // Set elements to variables
    let current = self.preview.get(0);
    let other = self.edit.get(0);

    // Calculate the position of scroll position based on percentage
    let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);

    // Set the scroll position on the other pane
    other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);

});
Answer

I know this is an old thread, but maybe this will help someone. In case if you need to synchronize scrolling in double direction, it's not good enough to just handle both containers' scrolling events and set the scroll value, because then scrolling events are getting into cycle and the scrolling is not smooth (try to scroll vertically by a mouse wheel an example given by Hightom).

Here is an example of how you can check if you are already synchronizing the scroll:

var isSyncingLeftScroll = false;
var isSyncingRightScroll = false;
var leftDiv = document.getElementById('left');
var rightDiv = document.getElementById('right');

leftDiv.onscroll = function() {
  if (!isSyncingLeftScroll) {
    isSyncingRightScroll = true;
    rightDiv.scrollTop = this.scrollTop;
  }
  isSyncingLeftScroll = false;
}

rightDiv.onscroll = function() {
  if (!isSyncingRightScroll) {
    isSyncingLeftScroll = true;
    leftDiv.scrollTop = this.scrollTop;
  }
  isSyncingRightScroll = false;
}
.container {
  width: 200px;
  height: 500px;
  overflow-y: auto;
}

.leftContainer {
  float: left;
}

.rightContainer {
  float: right;
}
<div id="left" class="container leftContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>
<div id="right" class="container rightContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>

Here is the fiddle.

Answer

I've been looking for a double direction solution and thanks to you all, your contibutions helped me doing this :

$('#cells').on('scroll', function () {
$('#hours').scrollTop($(this).scrollTop());
$('#days').scrollLeft($(this).scrollLeft());});

See on JSFiddle : https://jsfiddle.net/sgcer/1274/

Hope it's help someone someday :-)

Answer

Thanks to the answers above, I made a mixed solution that works preferentially for me:

var isLeftScrollTopCalled = false;
$('#leftElement').scroll(function (e) {
    if (isRightScrollTopCalled) {
        return isRightScrollTopCalled = false;
    }

    $('#rightElement').scrollTop($(this).scrollTop());
    isLeftScrollTopCalled = true;
});

var isRightScrollTopCalled = false;
$('#rightElement').scroll(function (e) {
    if (isLeftScrollTopCalled) {
        return isLeftScrollTopCalled = false;
    }

    $('#leftElement').scrollTop($(this).scrollTop());
    isRightScrollTopCalled = true;
});
Answer

Another solution that prevents this looping problem and achieves a smooth scroll. This makes sure that only the focused element gets the scroll event.

let activePre: HTMLPreElement = null;
document.querySelectorAll(".scrollable-pre").forEach(function(pre: HTMLPreElement) {
    pre.addEventListener("mouseenter", function(e: MouseEvent) {
        let pre = e.target as HTMLPreElement;
        activePre = pre;
    });

    pre.addEventListener("scroll", function(e: MouseEvent) {
        let pre = e.target as HTMLPreElement;

        if (activePre !== pre) {
            return;
        }

        if (pre !== versionBasePre) {
            versionBasePre.scrollTop = pre.scrollTop;
            versionBasePre.scrollLeft = pre.scrollLeft;
        }

        if (pre !== versionCurrentPre) {
            versionCurrentPre.scrollTop = pre.scrollTop;
            versionCurrentPre.scrollLeft = pre.scrollLeft;
        }

    });
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.