Last active
November 2, 2024 03:53
-
-
Save drwpow/17f34dc5043a31017f6bbc8485f0da3c to your computer and use it in GitHub Desktop.
Performant, 60FPS smooth scrolling in Vanilla JavaScript using requestAnimationFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} yPos Pixels from the top of the screen to scroll to | |
* @param {number} duration Time of animation in milliseconds | |
*/ | |
const scrollTo = (yPos, duration = 600) => { | |
const startY = window.scrollY; | |
const difference = yPos - startY; | |
const startTime = performance.now(); | |
const step = () => { | |
const progress = (performance.now() - startTime) / duration; | |
const amount = easeOutCubic(progress); | |
window.scrollTo({ top: startY + amount * difference }); | |
if (progress < 0.99) { | |
window.requestAnimationFrame(step); | |
} | |
}; | |
step(); | |
} | |
// Easing function from https://gist.github.com/gre/1650294 | |
const easeOutCubic = t => --t * t * t + 1; |
Adapted this slightly, mainly to be promise based. Have found it to be a reliable way to know when the scroll has finished:
export const smoothScrollTo = (
y: number,
{duration = 400, offset = 0} = {}
) => {
const easeOutCubic = (t: number) => --t * t * t + 1;
const startY = window.scrollY;
const difference = y - startY;
const startTime = performance.now();
if (y === startY + offset) {
return Promise.resolve(undefined);
}
return new Promise((resolve) => {
const step = () => {
const progress = (performance.now() - startTime) / duration;
const amount = easeOutCubic(progress);
window.scrollTo({top: startY + amount * difference - offset});
if (progress < 0.99) {
window.requestAnimationFrame(step);
} else {
resolve(undefined);
}
};
step();
});
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Snippet made to be used with react-scroll-agent (which provides
window.scrollY
values)