-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
74 lines (62 loc) · 2.04 KB
/
index.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var GAP = 10;
// [TODO]: DRY
var scrollToTop = function(scrollDuration) {
var scrollHeight = window.pageYOffset;
var scrollStep = Math.PI / (scrollDuration / 15);
var cosParameter = scrollHeight / 2;
var scrollCount = 0;
var scrollMargin;
var scrollPosition;
var scrollInterval = setInterval(function() {
if (window.pageYOffset != 0) {
scrollCount = scrollCount + 1;
scrollMargin =
cosParameter - cosParameter * Math.cos(scrollCount * scrollStep);
if (scrollHeight - scrollMargin > scrollPosition) {
clearInterval(scrollInterval);
scrollToTop(scrollDuration / scrollCount);
}
scrollPosition = scrollHeight - scrollMargin;
window.scrollTo(0, scrollPosition);
} else {
clearInterval(scrollInterval);
}
}, 15);
};
var scrollToElement = function(element, interval, options) {
var offset = getElementOffset(element);
var initialOffset = window.pageYOffset;
var scrollHeight = offset - initialOffset;
var scrollStep = Math.PI / (interval / 15);
var cosParameter = scrollHeight / 2;
var scrollCount = 0;
var scrollMargin;
var previousScrollMargin;
var signChanged = false;
var gap = options && options.gap ? options.gap : GAP;
var scrollInterval = setInterval(function() {
// Elelement we want to scroll to below current scroll position
if (
(window.pageYOffset < offset - gap || window.pageYOffset > offset) &&
!signChanged
) {
scrollCount = scrollCount + 1;
scrollMargin =
cosParameter - cosParameter * Math.cos(scrollCount * scrollStep);
if (previousScrollMargin) {
signChanged = Math.abs(scrollMargin) < Math.abs(previousScrollMargin);
}
window.scrollTo(0, initialOffset + scrollMargin - gap);
previousScrollMargin = scrollMargin;
} else {
clearInterval(scrollInterval);
}
}, 15);
};
var getElementOffset = function(element) {
return window.pageYOffset + element.getBoundingClientRect().top;
};
module.exports = {
scrollToTop: scrollToTop,
scrollTo: scrollToElement
};