Created
March 24, 2020 01:31
-
-
Save codexico/1a551fe4cc3fb84481e93dce52724372 to your computer and use it in GitHub Desktop.
helper to animate 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
let newAnimationId = 0; | |
export function animateScrollTo(el, to, duration) { | |
const init = el.scrollTop; | |
const startTime = performance.now(); | |
let direction = to < init; | |
let change = 0; | |
if (direction) { | |
change = init - to; | |
} else { | |
change = to - init; | |
} | |
function animate(animationId) { | |
if (animationId < newAnimationId) { | |
return; | |
} | |
const elapsed = (performance.now() - startTime); | |
const percentTime = elapsed / duration; | |
let newTop = direction | |
? init - (change * percentTime) | |
: init + (change * percentTime); | |
if ((!direction && (newTop >= to)) | |
|| (direction && (newTop <= to))) { | |
return; | |
} | |
window.requestAnimationFrame(function animationStep() { | |
el.scrollTop = newTop; | |
animate(animationId); | |
}); | |
} | |
animate(++newAnimationId); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment