Skip to content

Instantly share code, notes, and snippets.

@harryandriyan
Created March 14, 2019 04:24
Show Gist options
  • Save harryandriyan/944322c3a0487a80f3b17eb1701184fe to your computer and use it in GitHub Desktop.
Save harryandriyan/944322c3a0487a80f3b17eb1701184fe to your computer and use it in GitHub Desktop.
Scroll export version
export const smoothScroll = eID => {
const currentYPosition = () => {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
const elmYPosition = (eID) => {
const elm = document.getElementById(eID);
const y = elm.offsetTop;
const node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
const startY = currentYPosition();
const stopY = elmYPosition(eID);
const distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
const speed = 1000;
const step = Math.round(distance / 25);
const leapY = stopY > startY ? startY + step : startY - step;
const timer = 0;
if (stopY > startY) {
for ( let i=startY; i<stopY; i+=step ) {
setTimeout(`window.scrollTo(0, ${leapY})`, timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( let i=startY; i>stopY; i-=step ) {
setTimeout(`window.scrollTo(0, ${leapY})`, timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment