Skip to content

Instantly share code, notes, and snippets.

@deguchi
Last active June 12, 2021 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deguchi/9cf3e612aa41a3d79ab9c4d4200ffc10 to your computer and use it in GitHub Desktop.
Save deguchi/9cf3e612aa41a3d79ab9c4d4200ffc10 to your computer and use it in GitHub Desktop.
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