-
Notifications
You must be signed in to change notification settings - Fork 3
/
inviewport.ts
64 lines (59 loc) · 1.56 KB
/
inviewport.ts
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
/**
* inViewport.
*
* @format
*/
interface OberverConfig {
root?: Element | null;
rootMargin?: string;
threshold?: number | number[];
}
export default function inViewport(
element: HTMLElement,
threshold: number | number[],
callback: Function | Function[],
advancedConfiguration: OberverConfig | null = null
): void {
if ('IntersectionObserver' in window && element) {
const safeRoot =
advancedConfiguration && advancedConfiguration.root
? advancedConfiguration.root
: null;
const safeRootMargin =
advancedConfiguration && advancedConfiguration.rootMargin
? advancedConfiguration.rootMargin
: '0px';
const config: OberverConfig = {
root: safeRoot,
rootMargin: safeRootMargin,
threshold:
(Array.isArray(threshold) && threshold.length > 0) ||
(threshold >= 0 && threshold <= 1)
? threshold
: 0.5,
};
/**
* Observer.
*/
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((change) => {
if (change.intersectionRatio > 0) {
if (Array.isArray(callback)) {
callback[0]();
if (callback.length === 1) {
observer.unobserve(change.target);
}
} else {
callback();
}
}
if (change.isIntersecting === false) {
if (Array.isArray(callback) && typeof callback[1] === 'function') {
callback[1]();
}
}
});
}, config);
observer.observe(element);
}
}