Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scroll to element or scroll by value
let rafId;
function scrollToElement(el, offsetTop = 0) {
scrollByValue(el.getBoundingClientRect().top - offsetTop);
}
function scrollByValue(offsetTop = 0) {
if (offsetTop !== 0) {
if (rafId) {
cancelAnimationFrame(rafId);
}
rafId = requestAnimationFrame(scrollStep.bind(null, offsetTop));
}
}
function scrollStep(totalDistance) {
const speed = 0.085;
const totalDistansAbs = Math.abs(totalDistance);
let stepSize = parseInt(speed * totalDistansAbs, 10);
if (stepSize < 4) {
stepSize = totalDistansAbs < 4 ? totalDistansAbs : 4;
}
if (totalDistance > 0) {
totalDistance -= stepSize;
window.scrollBy(0, stepSize);
} else {
totalDistance += stepSize;
window.scrollBy(0, -stepSize);
}
if (totalDistance !== 0) {
rafId = requestAnimationFrame(scrollStep.bind(null, totalDistance));
}
}
export default {
scrollToElement,
scrollByValue
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.