Skip to content

Instantly share code, notes, and snippets.

@kdzwinel
Created May 2, 2017 10:24
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kdzwinel/f1fd8268fdf32a041e43d96dc6c005c8 to your computer and use it in GitHub Desktop.
Save kdzwinel/f1fd8268fdf32a041e43d96dc6c005c8 to your computer and use it in GitHub Desktop.
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