-
Notifications
You must be signed in to change notification settings - Fork 57
/
animatedScrollTo.js
50 lines (46 loc) · 1.68 KB
/
animatedScrollTo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
(function (window) {
var requestAnimFrame = (function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})();
var easeInOutQuad = function (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
var animatedScrollTo = function (element, to, duration, callback) {
var start = element.scrollTop,
change = to - start,
animationStart = +new Date();
var animating = true;
var lastpos = null;
var animateScroll = function() {
if (!animating) {
return;
}
requestAnimFrame(animateScroll);
var now = +new Date();
var val = Math.floor(easeInOutQuad(now - animationStart, start, change, duration));
if (lastpos) {
if (lastpos === element.scrollTop) {
lastpos = val;
element.scrollTop = val;
} else {
animating = false;
}
} else {
lastpos = val;
element.scrollTop = val;
}
if (now > animationStart + duration) {
element.scrollTop = to;
animating = false;
if (callback) { callback(); }
}
};
requestAnimFrame(animateScroll);
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = animatedScrollTo;
} else {
window.animatedScrollTo = animatedScrollTo;
}
})(window);