Skip to content

Instantly share code, notes, and snippets.

@dmail
Created September 16, 2020 17:01
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 dmail/d1d6528c93191adf0b2ab5fcdb892222 to your computer and use it in GitHub Desktop.
Save dmail/d1d6528c93191adf0b2ab5fcdb892222 to your computer and use it in GitHub Desktop.
Animation in javascript
document.querySelector('button').onclick = () => {
const scrollStart = document.querySelector(".menu-wrapper").scrollLeft
const scrollEnd = scrollStart + menuWrapperSize
startJavaScriptAnimation({
duration: 300,
onProgress: ({ progress }) => {
document.querySelector(".menu-wrapper").scrollLeft =
scrollStart + (scrollEnd - scrollStart) * progress
},
})
}
export const startJavaScriptAnimation = ({
duration = 300,
timingFunction = (t) => t,
onProgress = () => {},
onCancel = () => {},
onComplete = () => {},
}) => {
if (isNaN(duration)) {
// console.warn(`duration must be a number, received ${duration}`)
return () => {}
}
duration = parseInt(duration, 10)
const startMs = performance.now()
let currentRequestAnimationFrameId
let done = false
let rawProgress = 0
let progress = 0
const handler = () => {
currentRequestAnimationFrameId = null
const nowMs = performance.now()
rawProgress = Math.min((nowMs - startMs) / duration, 1)
progress = timingFunction(rawProgress)
done = rawProgress === 1
onProgress({
done,
rawProgress,
progress,
})
if (done) {
onComplete()
} else {
currentRequestAnimationFrameId = window.requestAnimationFrame(handler)
}
}
handler()
const stop = () => {
if (currentRequestAnimationFrameId) {
window.cancelAnimationFrame(currentRequestAnimationFrameId)
currentRequestAnimationFrameId = null
}
if (!done) {
done = true
onCancel({
rawProgress,
progress,
})
}
}
return stop
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment