Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. export const smoothScroll = eID => {
  2. const currentYPosition = () => {
  3. // Firefox, Chrome, Opera, Safari
  4. if (self.pageYOffset) return self.pageYOffset;
  5. // Internet Explorer 6 - standards mode
  6. if (document.documentElement && document.documentElement.scrollTop)
  7. return document.documentElement.scrollTop;
  8. // Internet Explorer 6, 7 and 8
  9. if (document.body.scrollTop) return document.body.scrollTop;
  10. return 0;
  11. }
  12.  
  13.  
  14. const elmYPosition = (eID) => {
  15. const elm = document.getElementById(eID);
  16. const y = elm.offsetTop;
  17. const node = elm;
  18. while (node.offsetParent && node.offsetParent != document.body) {
  19. node = node.offsetParent;
  20. y += node.offsetTop;
  21. } return y;
  22. }
  23.  
  24. const startY = currentYPosition();
  25. const stopY = elmYPosition(eID);
  26. const distance = stopY > startY ? stopY - startY : startY - stopY;
  27.  
  28. if (distance < 100) {
  29. scrollTo(0, stopY); return;
  30. }
  31.  
  32. const speed = 1000;
  33. const step = Math.round(distance / 25);
  34. const leapY = stopY > startY ? startY + step : startY - step;
  35. const timer = 0;
  36. if (stopY > startY) {
  37. for ( let i=startY; i<stopY; i+=step ) {
  38. setTimeout(`window.scrollTo(0, ${leapY})`, timer * speed);
  39. leapY += step; if (leapY > stopY) leapY = stopY; timer++;
  40. } return;
  41. }
  42. for ( let i=startY; i>stopY; i-=step ) {
  43. setTimeout(`window.scrollTo(0, ${leapY})`, timer * speed);
  44. leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement