DEV Community

Cover image for Locking scroll of multiple containers simultaneously
Jyotirmaya Sahu
Jyotirmaya Sahu

Posted on

Locking scroll of multiple containers simultaneously

Hi Friends! Every one of us must have seen the commit comparer of Github or some other source control providers. There, we have two containers scrolling simultaneously so that we can have a look at
the same place of both the files at the same time.

I am talking of something like this...
Notepad++ Code Compare

Achieving this in the web is quite simple, with JavaScript and Css.

I have made an example but it's horizontal. Yes! It seems quite odd but the main thing I wanna showcase here is the scrolling.

Here, we can assign a scroll event listener to the scroll sections or containers and access the scrollLeft property of the scroll target.

f.addEventListener('scroll', (e) => {
    console.log(e.target.scrollLeft);
  }
});
Enter fullscreen mode Exit fullscreen mode

Now we assign the scrollLeft value to our second container's scrollLeft, and we have a working demo. And yes, we can do the same for the first container as well so that scrolling the second container will also scroll the first.

f.addEventListener('scroll', (e) => {
    s.scrollLeft = e.target.scrollLeft;
  }
});
Enter fullscreen mode Exit fullscreen mode

But, now we have an issue. We can surely notice the stuttering of the scroll-bar. It's not smooth anymore. This is because setting the scrollLeft value of any container will trigger the scroll event on it.

To tackle this, we utilize debouncing. We maintain two variables, isFirstScrolling and isSecondScrolling. We use this to track whether the other one is scrolling, and we can update the scroll position of that container. If it is scrolling, we should not update the scroll value, this causes the stuttering.

f.addEventListener('scroll', (e) => {
  if(!isSecondScrolling) {
    isFirstScrolling = true;
    customDebounce("first");
    s.scrollLeft = e.target.scrollLeft;
  }
});

s.addEventListener('scroll', (e) => {
  if(!isFirstScrolling) {
    isSecondScrolling = true;
    customDebounce("second");
    f.scrollLeft = e.target.scrollLeft;
  }
});
Enter fullscreen mode Exit fullscreen mode

The customDebounce function helps to set the scroll trackers to false once scrolling is over.

let timeOut;

const customDebounce = (tracker) => {
  console.log(timeOut);
  clearTimeout(timeOut);
  console.log("cleared",timeOut);
  timeOut = setTimeout(() => {
    if(tracker === "first")
      isFirstScrolling = !isFirstScrolling;
    else
      isSecondScrolling = !isSecondScrolling;
  }, 700);
}
Enter fullscreen mode Exit fullscreen mode

So, with this, we have our working example.

Kindly check out the code and give valuable feedback to improve my further posts.

Thank You.

Top comments (0)