Skip to content

Instantly share code, notes, and snippets.

@zecar
Created May 22, 2020 13:22
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 zecar/5585eb9ceca355d91b0967578903342b to your computer and use it in GitHub Desktop.
Save zecar/5585eb9ceca355d91b0967578903342b to your computer and use it in GitHub Desktop.
quick smooth scroll
// smooth scroll
var now = window.performance && window.performance.now ? window.performance.now.bind(window.performance): Date.now
var SCROLL_TIME = 468
export function smoothScrollTo({ element, y, startY, startTime }) {
startTime = startTime || now()
var time = now()
var elapsed = (time - startTime) / SCROLL_TIME;
// avoid elapsed times higher than one
elapsed = elapsed > 1 ? 1 : elapsed
// apply easing to elapsed time
var value = 0.5 * (1 - Math.cos(Math.PI * elapsed))
var currentY = startY + (y - startY) * value
element.scrollTop = currentY
// scroll more if we have not reached our destination
if (currentY !== y) {
window.requestAnimationFrame(smoothScrollTo.bind(window, { element, y, startY, startTime }))
}
}
smoothScrollTo({
element: domElement,
y: 100,
startY: domElement.scrollTop
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment