anim.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // first add raf shim
  2. // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  3. window.requestAnimFrame = (function(){
  4. return window.requestAnimationFrame ||
  5. window.webkitRequestAnimationFrame ||
  6. window.mozRequestAnimationFrame ||
  7. function( callback ){
  8. window.setTimeout(callback, 1000 / 60);
  9. };
  10. })();
  11. // main function
  12. function scrollToY(scrollTargetY, speed, easing) {
  13. // scrollTargetY: the target scrollY property of the window
  14. // speed: time in pixels per second
  15. // easing: easing equation to use
  16. var scrollY = window.scrollY,
  17. scrollTargetY = scrollTargetY || 0,
  18. speed = speed || 2000,
  19. easing = easing || 'easeOutSine',
  20. currentTime = 0;
  21. // min time .1, max time .8 seconds
  22. var time = Math.max(.1, Math.min(Math.abs(scrollY - scrollTargetY) / speed, .8));
  23. // easing equations from https://github.com/danro/easing-js/blob/master/easing.js
  24. var PI_D2 = Math.PI / 2,
  25. easingEquations = {
  26. easeOutSine: function (pos) {
  27. return Math.sin(pos * (Math.PI / 2));
  28. },
  29. easeInOutSine: function (pos) {
  30. return (-0.5 * (Math.cos(Math.PI * pos) - 1));
  31. },
  32. easeInOutQuint: function (pos) {
  33. if ((pos /= 0.5) < 1) {
  34. return 0.5 * Math.pow(pos, 5);
  35. }
  36. return 0.5 * (Math.pow((pos - 2), 5) + 2);
  37. }
  38. };
  39. // add animation loop
  40. function tick() {
  41. currentTime += 1 / 60;
  42. var p = currentTime / time;
  43. var t = easingEquations[easing](p);
  44. if (p < 1) {
  45. requestAnimFrame(tick);
  46. window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t));
  47. } else {
  48. window.scrollTo(0, scrollTargetY);
  49. }
  50. }
  51. // call it once to get started
  52. tick();
  53. }