Created
April 10, 2020 18:53
-
-
Save Aliath/fb1861f2bba065258baa912f2b917133 to your computer and use it in GitHub Desktop.
Function which works as window.scrollTo(0, y), but much prettier. :)
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
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