Created
May 22, 2020 13:22
-
-
Save zecar/5585eb9ceca355d91b0967578903342b to your computer and use it in GitHub Desktop.
quick smooth scroll
This file contains 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
// 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