UNPKG

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