Skip to content

Instantly share code, notes, and snippets.

@PsyGik
Forked from drwpow/smooth-scrolling.js
Created August 17, 2019 18:30
Show Gist options
  • Save PsyGik/1458a9e3de79049741d228d145c2cf60 to your computer and use it in GitHub Desktop.
Save PsyGik/1458a9e3de79049741d228d145c2cf60 to your computer and use it in GitHub Desktop.
Performant, 60FPS smooth scrolling in Vanilla JavaScript using requestAnimationFrame
/**
* @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