Skip to content

Instantly share code, notes, and snippets.

@codexico
Created March 24, 2020 01:31
Show Gist options
  • Save codexico/1a551fe4cc3fb84481e93dce52724372 to your computer and use it in GitHub Desktop.
Save codexico/1a551fe4cc3fb84481e93dce52724372 to your computer and use it in GitHub Desktop.
helper to animate scroll
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