scroll-to.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. Math.easeInOutQuad = function(t, b, c, d) {
  2. t /= d / 2
  3. if (t < 1) {
  4. return (c / 2) * t * t + b
  5. }
  6. t--
  7. return (-c / 2) * (t * (t - 2) - 1) + b
  8. }
  9. // requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
  10. var requestAnimFrame = (function() {
  11. return (
  12. window.requestAnimationFrame ||
  13. window.webkitRequestAnimationFrame ||
  14. window.mozRequestAnimationFrame ||
  15. function(callback) {
  16. window.setTimeout(callback, 1000 / 60)
  17. }
  18. )
  19. })()
  20. /**
  21. * Because it's so fucking difficult to detect the scrolling element, just move them all
  22. * @param {number} amount
  23. */
  24. function move(amount) {
  25. document.documentElement.scrollTop = amount
  26. document.body.parentNode.scrollTop = amount
  27. document.body.scrollTop = amount
  28. }
  29. function position() {
  30. return (
  31. document.documentElement.scrollTop ||
  32. document.body.parentNode.scrollTop ||
  33. document.body.scrollTop
  34. )
  35. }
  36. /**
  37. * @param {number} to
  38. * @param {number} duration
  39. * @param {Function} callback
  40. */
  41. export function scrollTo(to, duration, callback) {
  42. const start = position()
  43. const change = to - start
  44. const increment = 20
  45. let currentTime = 0
  46. duration = typeof duration === 'undefined' ? 500 : duration
  47. var animateScroll = function() {
  48. // increment the time
  49. currentTime += increment
  50. // find the value with the quadratic in-out easing function
  51. var val = Math.easeInOutQuad(currentTime, start, change, duration)
  52. // move the document.body
  53. move(val)
  54. // do the animation unless its over
  55. if (currentTime < duration) {
  56. requestAnimFrame(animateScroll)
  57. } else {
  58. if (callback && typeof callback === 'function') {
  59. // the animation is done so lets callback
  60. callback()
  61. }
  62. }
  63. }
  64. animateScroll()
  65. }