Skip to content

Instantly share code, notes, and snippets.

@jiayihu
Created December 8, 2017 20:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiayihu/049a42dc4505290af98c196d3ef2e430 to your computer and use it in GitHub Desktop.
Save jiayihu/049a42dc4505290af98c196d3ef2e430 to your computer and use it in GitHub Desktop.
Pure JS animated scrollTop using requestAnimationFrame
export function animateScrollTop(element: HTMLElement, value: number, timing: number) {
let start: number = null;
let animationToken: number;
const valueSign = value >= 0 ? 1 : -1;
const currentScroll = element.scrollTop;
const step = (timestamp: number) => {
if (!start) {
start = timestamp;
}
const progress = timestamp - start;
const stepValue = Math.min(Math.abs((progress / timing) * value), Math.abs(value));
element.scrollTop = currentScroll + (valueSign * stepValue);
if (progress < timing) {
window.requestAnimationFrame(step);
} else {
window.cancelAnimationFrame(animationToken);
}
};
animationToken = window.requestAnimationFrame(step);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment