Skip to content

Instantly share code, notes, and snippets.

@Aliath
Created April 10, 2020 18:53
Show Gist options
  • Save Aliath/fb1861f2bba065258baa912f2b917133 to your computer and use it in GitHub Desktop.
Save Aliath/fb1861f2bba065258baa912f2b917133 to your computer and use it in GitHub Desktop.
Function which works as window.scrollTo(0, y), but much prettier. :)
export const animatedScrollTo = (scrollValue: number, duration: number = 350): void =>
{
const value = Math.max(0, scrollValue);
const animationStart = performance.now();
const currentScroll = window.pageYOffset;
const scrollDelta = value - currentScroll;
const update = (): void =>
{
const currentTimestamp = performance.now();
if (currentTimestamp >= animationStart + duration)
{
window.scrollTo(0, value);
return;
}
requestAnimationFrame(update);
const percentageFinished = (currentTimestamp - animationStart) / duration;
window.scrollTo(0, currentScroll + percentageFinished * scrollDelta);
};
requestAnimationFrame(update);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment