Skip to content

Instantly share code, notes, and snippets.

@jl-welch
Last active July 26, 2019 00:55
Show Gist options
  • Save jl-welch/0e3d608a9a741b3a19ed0c7418314d88 to your computer and use it in GitHub Desktop.
Save jl-welch/0e3d608a9a741b3a19ed0c7418314d88 to your computer and use it in GitHub Desktop.
Simple example of smooth scrolling using vanilla JS
const duration = 0.06 * 800; // 800ms (60fps)
const from = scrollY;
const to = document.documentElement.scrollHeight;
const change = to - from;
let time = 0;
function ease(change, duration, from, time) {
time /= duration / 2;
if (time < 1) {
return change / 2 * time * time + from;
}
time--;
return -change / 2 * (time * (time - 2) - 1) + from;
}
function smoothScroll() {
if (time >= duration) {
return;
}
requestAnimationFrame(smoothScroll);
const y = ease(change, duration, from, ++time);
scrollTo(0, y);
}
smoothScroll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment