scroll-to.js 1.7 KB

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