scroll-to.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. const requestAnimFrame = (function() {
  11. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
  12. window.setTimeout(callback, 1000 / 60)
  13. }
  14. })()
  15. /**
  16. * Because it's so fucking difficult to detect the scrolling element, just move them all
  17. * @param {number} amount
  18. */
  19. function move(amount) {
  20. document.documentElement.scrollTop = amount
  21. document.body.parentNode.scrollTop = amount
  22. document.body.scrollTop = amount
  23. }
  24. function position() {
  25. return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
  26. }
  27. /**
  28. * @param {number} to
  29. * @param {number} duration
  30. * @param {Function} callback
  31. */
  32. export function scrollTo(to, duration, callback) {
  33. const start = position()
  34. const change = to - start
  35. const increment = 20
  36. let currentTime = 0
  37. duration = (typeof (duration) === 'undefined') ? 500 : duration
  38. const animateScroll = function() {
  39. // increment the time
  40. currentTime += increment
  41. // find the value with the quadratic in-out easing function
  42. const val = Math.easeInOutQuad(currentTime, start, change, duration)
  43. // move the document.body
  44. move(val)
  45. // do the animation unless its over
  46. if (currentTime < duration) {
  47. requestAnimFrame(animateScroll)
  48. } else {
  49. if (callback && typeof (callback) === 'function') {
  50. // the animation is done so lets callback
  51. callback()
  52. }
  53. }
  54. }
  55. animateScroll()
  56. }