1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | var attribute = 'data-scrolldir';
|
9 | var dir = 'down';
|
10 |
|
11 | var thresholdPixels = 64;
|
12 |
|
13 | var el = document.documentElement;
|
14 | var win = window;
|
15 | var body = document.body;
|
16 | var historyLength = 32;
|
17 |
|
18 | var historyMaxAge = 512;
|
19 |
|
20 | var history = Array(historyLength);
|
21 | var e;
|
22 |
|
23 | var pivot;
|
24 |
|
25 | var pivotTime = 0;
|
26 |
|
27 | function tick() {
|
28 | var y = win.scrollY || win.pageYOffset;
|
29 | var t = e.timeStamp;
|
30 | var furthest = dir === 'down' ? Math.max : Math.min;
|
31 |
|
32 | var yMax = body.scrollHeight - win.innerHeight;
|
33 | y = Math.max(0, y);
|
34 | y = Math.min(yMax, y);
|
35 |
|
36 | history.unshift({
|
37 | y: y,
|
38 | t: t
|
39 | });
|
40 | history.pop();
|
41 |
|
42 | if (y === furthest(pivot, y)) {
|
43 |
|
44 | pivotTime = t;
|
45 | pivot = y;
|
46 | return;
|
47 | }
|
48 |
|
49 |
|
50 |
|
51 | var cutoffTime = t - historyMaxAge;
|
52 |
|
53 | if (cutoffTime > pivotTime) {
|
54 | pivot = y;
|
55 |
|
56 | for (var i = 0; i < historyLength; i += 1) {
|
57 | if (!history[i] || history[i].t < cutoffTime) break;
|
58 | pivot = furthest(pivot, history[i].y);
|
59 | }
|
60 | }
|
61 |
|
62 |
|
63 | if (Math.abs(y - pivot) > thresholdPixels) {
|
64 | pivot = y;
|
65 | pivotTime = t;
|
66 | dir = dir === 'down' ? 'up' : 'down';
|
67 | el.setAttribute(attribute, dir);
|
68 | }
|
69 | }
|
70 |
|
71 | function handler(event) {
|
72 | e = event;
|
73 | return win.requestAnimationFrame(tick);
|
74 | }
|
75 |
|
76 | function scrollDir(opts) {
|
77 | if (opts) {
|
78 | if (opts.attribute) attribute = opts.attribute;
|
79 | if (opts.el) el = opts.el;
|
80 | if (opts.win) win = opts.win;
|
81 | if (opts.dir) dir = opts.dir;
|
82 | if (opts.thresholdPixels) thresholdPixels = opts.thresholdPixels;
|
83 |
|
84 |
|
85 |
|
86 | if (opts.off === true) {
|
87 | el.setAttribute(attribute, 'off');
|
88 | return win.removeEventListener('scroll', handler);
|
89 | }
|
90 | }
|
91 |
|
92 |
|
93 |
|
94 |
|
95 | pivot = win.scrollY || win.pageYOffset;
|
96 | el.setAttribute(attribute, dir);
|
97 | return win.addEventListener('scroll', handler);
|
98 | }
|
99 |
|
100 | export default scrollDir;
|