Created
December 8, 2017 20:01
-
-
Save jiayihu/049a42dc4505290af98c196d3ef2e430 to your computer and use it in GitHub Desktop.
Pure JS animated scrollTop using requestAnimationFrame
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
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