-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (51 loc) · 1.76 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
const root = document.getElementById('root');
const container = document.getElementById('container');
const observable = document.getElementById('observable');
console.log(root, container, observable);
class IntersectionObserver{
constructor(root){
this.root = root;
this.observables = new Map();
this.init();
this.visibleElements = new Set();
}
scroll=(e)=>{
const rootScrollTop = this.root.scrollTop;
const rootClientHeight = this.root.clientHeight;
this.observables.forEach((callback, element)=>{
const elementOffsetTop = element.offsetTop;
const elementClientHeight = element.clientHeight;
const isVisible = rootScrollTop <= elementOffsetTop + elementClientHeight
&& elementOffsetTop <=rootClientHeight + rootScrollTop;
if(isVisible){
if(!this.visibleElements.has(element)){
callback('true', element);
this.visibleElements.add(element);
}
}
else{
if(this.visibleElements.has(element)){
this.visibleElements.delete(element);
callback('false', element);
}
}
})
}
init(){
this.root.addEventListener('scroll', this.scroll);
}
addObservable(el, cb){
this.observables.set(el, cb);
}
removeObservable(el){
this.observables.delete(el);
}
decompose(){
this.root.removeObservable('scroll', this.scroll);
}
};
const intersectionObserver = new IntersectionObserver(root);
intersectionObserver.addObservable(observable, (status, element)=>{
console.log(status, element);
})
console.log(intersectionObserver);