-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrollEventAgent.js
52 lines (47 loc) · 1.09 KB
/
scrollEventAgent.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
/*
* Trigger system for animations on specific scroll positions.
* Distributed under the MIT license.
* (c) 2020 Florian Beck
*/
export default class ScrollEventAgent {
constructor(framerate) {
this.events = {};
this.scrollPos = 0;
this.framerate = framerate;
}
addEvent(trigger, callback, delay = 0){
if (!(trigger in this.events)) {
this.events[trigger] = [];
}
this.events[trigger].push({
event: callback,
delay: delay,
});
}
removeEvent(trigger, callback){
if (!(trigger in this.events)) {
return;
}
for(let i in this.events[trigger]) {
if (this.events[trigger][i].event === callback) {
this.events[trigger].splice(i, 1);
return;
}
}
}
scroll(delta) {
if (delta > 0) {
this.scrollPos++;
} else if (this.scrollPos > 0) {
this.scrollPos--;
}
if (!(this.scrollPos in this.events)) {
return;
}
for(let elem of this.events[this.scrollPos]) {
setTimeout(() => {
elem.event.call(this, delta);
}, elem.delay * 1000);
}
}
}