Sunday, February 25, 2018

Scroll Two Divs Together

Recently in one of my project there was a requirement to maintain scroll positions of two divs. In UI there are two divs side by side. If user scrolls on left DIV then right div should also be scrolled and if user scrolls on right DIV then left div should also be scrolled. So here is how to do this.

var leftPart = document.getElementById('leftPart');
var rightPart = document.getElementById('rightPart');

Now lets add scroll event on both.

leftPart.onscroll = function() {
    rightPart.scrollTop = this.scrollTop;
}

rightPart.onscroll = function() {
    leftPart.scrollTop = this.scrollTop;
}

That's it now both should scroll no but wait it makes your UI unresponsive because there is a deadlock. While right one is scrolling, it will also scroll left one and at the same time it will also fire event and will try  to scroll right one again and there is DEADLOCK.........

So to prevent it, we have to add flags to check if one is already scrolling then hold the event.

so lets have two flags.

var isSyncingLeftScroll = false;
var isSyncingRightScroll = false;

and use it in scroll event.

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

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

That's it and now you will have smooth scrolling effect on both the DIVs. Hope this helps you.

No comments:

Post a Comment