Last active
July 26, 2019 00:55
-
-
Save jl-welch/0e3d608a9a741b3a19ed0c7418314d88 to your computer and use it in GitHub Desktop.
Simple example of smooth scrolling using vanilla JS
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
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