forked from madebysource/animated-scrollto
-
Notifications
You must be signed in to change notification settings - Fork 4
/
animatedScrollTo.js
60 lines (53 loc) · 1.98 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
51
52
53
54
55
56
57
58
59
60
(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 || isBottomPage(element)) {
element.scrollTop = to;
animating = false;
if (callback) { callback(); }
}
};
requestAnimFrame(animateScroll);
var isBottomPage = function(element){
var scrollTop = element.scrollTop;
var scrolledToBottom = (scrollTop + window.innerHeight) >= element.scrollHeight;
if(scrolledToBottom){
return true;
}
}
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = animatedScrollTo;
} else {
window.animatedScrollTo = animatedScrollTo;
}
})(window);