Last active
June 12, 2021 01:00
-
-
Save deguchi/9cf3e612aa41a3d79ab9c4d4200ffc10 to your computer and use it in GitHub Desktop.
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
function scrollWindowBy(value: number, duration: number, easingFunc: (t: number) => number) { | |
let startTime: number | |
const startPos: number = window.scrollY | |
const clientHeight: number = window.innerHeight | |
const maxScroll = document.body.scrollHeight - clientHeight; | |
const scrollIntendedDestination = startPos + value; | |
// low and high bounds for possible scroll destinations | |
const scrollEndValue = Math.min(Math.max(scrollIntendedDestination, 0), maxScroll) | |
// create recursive function to call every frame | |
const scroll = (timestamp: number) => { | |
startTime = startTime || timestamp | |
const elapsed = timestamp - startTime | |
window.scrollTo(0, startPos + (scrollEndValue - startPos) * easingFunc(elapsed / duration)) | |
elapsed <= duration && window.requestAnimationFrame(scroll) | |
} | |
// call recursive function | |
if (startPos != scrollEndValue) window.requestAnimationFrame(scroll) | |
} | |
const easeInOutCubic = (t: number) => { | |
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 | |
} | |
scrollWindowBy(120, 1000, easeInOutCubic) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment