Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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++;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement