scrollTo.js 1.6 KB

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