Sync the scroll position of multiple elements on your page
npm install scrollmirror

bash
npm i scrollmirror
`
`js
import ScrollMirror from "scrollmirror";
`
Or include the minified production file from a CDN:
`html
`
Usage Example
Suppose you have the following HTML:
`html
`
This is how you would mirror the scroll position between the two div.scroller:
`js
import ScrollMirror from "scrollmirror";
/* Mirror all divs that match the class .scroller /
new ScrollMirror(document.querySelectorAll(".scroller"));
`
See also this minimal example on CodePen
š” To mirror the scroll position from and to the window, you would have to add one of :root, html or body to the selector:
`js
new ScrollMirror(document.querySelectorAll(":root, .scroller"));
/* or /
new ScrollMirror(document.querySelectorAll("html, .scroller"));
/* or /
new ScrollMirror(document.querySelectorAll("body, .scroller"));
`
Options
You can pass in a few additional options to ScrollMirror as the second argument:
`js
new ScrollMirror(document.querySelectorAll(".scroller"), options);
`
The type signature of the options object:
`js
type Options = {
vertical: boolean;
horizontal: boolean;
debug: boolean;
}
`
$3
Type: boolean, default: true. Should the vertical scroll position be mirrored?
$3
Type: boolean, default: true. Should the horizontal scroll position be mirrored?
$3
Type: boolean, default: true. Should debug messages be printed to the console?
API
To access ScrollMirror's API, you have to save a reference to the class during instaciation:
`js
const mirror = new ScrollMirror(document.querySelectorAll(".scroller"));
`
$3
Get the current scroll progress in the form of { x: number, y: number }, where both x and y are a
number between 0-1
$3
Set the progress and scrolls all mirrored elements. For example:
`js
// for both directions
mirror.progress = { x: 0.2, y: 0.5 };
// or only set one direction
mirror.progress = { y: 0.5 };
// or for both directions at once:
mirror.progress = 0.5;
`
$3
Get the current progress of an element. The element doesn't _need_ to be one of the mirrored elements
`ts
const mirror = new ScrollMirror(document.querySelectorAll(".scroller"));
// ...sometime later:
console.log(mirror.getScrollProgress(document.querySelector(":root")));
`
Motivation
There are already a few libraries out there that do the same thing. But all I could find had some limitations (For example, react-scroll-sync needs React, syncscroll doesn't provide an NPM package).
Also, this simple package gave me an excuse to play around with the tooling involved with creating a robust open source npm` package: