-
-
Save PsyGik/1458a9e3de79049741d228d145c2cf60 to your computer and use it in GitHub Desktop.
Performant, 60FPS smooth scrolling in Vanilla JavaScript using requestAnimationFrame
This file contains hidden or 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment