Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. export default (destination, duration = 200, easing = 'linear', callback) => {
  2. const easings = {
  3. linear(t) {
  4. return t;
  5. },
  6. easeInQuad(t) {
  7. return t * t;
  8. },
  9. easeOutQuad(t) {
  10. return t * (2 - t);
  11. },
  12. easeInOutQuad(t) {
  13. return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
  14. },
  15. easeInCubic(t) {
  16. return t * t * t;
  17. },
  18. easeOutCubic(t) {
  19. return (--t) * t * t + 1;
  20. },
  21. easeInOutCubic(t) {
  22. return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  23. },
  24. easeInQuart(t) {
  25. return t * t * t * t;
  26. },
  27. easeOutQuart(t) {
  28. return 1 - (--t) * t * t * t;
  29. },
  30. easeInOutQuart(t) {
  31. return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
  32. },
  33. easeInQuint(t) {
  34. return t * t * t * t * t;
  35. },
  36. easeOutQuint(t) {
  37. return 1 + (--t) * t * t * t * t;
  38. },
  39. easeInOutQuint(t) {
  40. return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
  41. }
  42. };
  43.  
  44. const start = window.pageYOffset;
  45. const startTime = 'now' in window.performance ? performance.now() : new Date().getTime();
  46.  
  47. const documentHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);
  48. const windowHeight = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
  49. const destinationOffset = typeof destination === 'number' ? destination : destination.offsetTop;
  50. const destinationOffsetToScroll = Math.round(documentHeight - destinationOffset < windowHeight ? documentHeight - windowHeight : destinationOffset);
  51.  
  52. if ('requestAnimationFrame' in window === false) {
  53. window.scroll(0, destinationOffsetToScroll);
  54. if (callback) {
  55. callback();
  56. }
  57. return;
  58. }
  59.  
  60. function scroll() {
  61. const now = 'now' in window.performance ? performance.now() : new Date().getTime();
  62. const time = Math.min(1, ((now - startTime) / duration));
  63. const timeFunction = easings[easing](time);
  64. window.scroll(0, Math.ceil((timeFunction * (destinationOffsetToScroll - start)) + start));
  65.  
  66. if (window.pageYOffset === destinationOffsetToScroll) {
  67. if (callback) {
  68. callback();
  69. }
  70. return;
  71. }
  72.  
  73. requestAnimationFrame(scroll);
  74. }
  75.  
  76. scroll();
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement