-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScrollBounds.js
85 lines (78 loc) · 2.48 KB
/
ScrollBounds.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
75
76
77
78
79
80
81
82
83
84
85
function ScrollBounds(w, d) {
var w = w || window,
d = d || document;
var body = d.body,
html = d.documentElement,
debug = false,
atTop = false,
atBottom = false,
reachBottomEvent = null,
leaveBottomEvent = null,
reachTopEvent = null,
leaveTopEvent = null;
var setDebug = function(value) {
debug = !! value;
};
var startListen = function() {
reachBottomEvent = new Event('scroll-reach-bottom');
leaveBottomEvent = new Event('scroll-leave-bottom');
reachTopEvent = new Event('scroll-reach-top');
leaveTopEvent = new Event('scroll-leave-top');
onScrolling();
w.addEventListener('scroll', listenScroll);
};
var stopListen = function() {
w.removeEventListener('scroll', listenScroll);
reachBottomEvent = null;
leaveBottomEvent = null;
reachTopEvent = null;
leaveTopEvent = null;
atTop = false;
atBottom = false;
};
var listenScroll = function() {
w.requestAnimationFrame(onScrolling);
};
var getValues = function() {
return {atTop: atTop, atBottom: atBottom};
}
var onScrolling = function() {
// margin pixels (it seems it's needed on mobile)
var isBottom = body.offsetHeight - (w.innerHeight + w.scrollY) < 3;
var isTop = (w.pageYOffset || body.scrollTop) < 2;
var hasChanged = false;
if (isBottom && ! atBottom) {
debug && console.log('reach bottom');
atBottom = true;
hasChanged = true;
html.dispatchEvent(reachBottomEvent);
} else if (! isBottom && atBottom) {
debug && console.log('leave bottom');
atBottom = false;
hasChanged = true;
html.dispatchEvent(leaveBottomEvent);
}
if (isTop && ! atTop) {
debug && console.log('reach top');
atTop = true;
hasChanged = true;
html.dispatchEvent(reachTopEvent);
} else if (! isTop && atTop) {
debug && console.log('leave top');
atTop = false;
hasChanged = true;
html.dispatchEvent(leaveTopEvent);
}
if (debug && hasChanged) {
console.log(getValues());
}
};
// auto start
startListen();
return {
get: getValues,
startListen: startListen,
stopListen: stopListen,
setDebug: setDebug
};
}