-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (55 loc) · 1.78 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
61
62
63
64
65
66
67
68
69
70
const IMPRESSION_DURATION_THRESHOLD = 1000;
const INTERSECTION_RATIO = 0.5;
const impressedItems = [];
const isAlreadyImpressedItem = (id) => impressedItems.includes(id);
let eventCount = 0;
const sendEvent = () => {
console.log(`event sent 💌 count: ${++eventCount}`);
};
const changeStatusImpressed = (targetElement, targetId) => {
targetElement.style.backgroundColor = "lightgreen";
impressedItems.push(targetId);
};
const changeStatusOnImpressing = (targetElement) => {
targetElement.style.backgroundColor = "lightcoral";
};
const changeStatusNotOnImpressing = (targetElement) => {
targetElement.style.backgroundColor = "skyblue";
};
const createCallback = () => {
let timeoutId = null;
return function callback(intersectionObserverEntries) {
intersectionObserverEntries.forEach((entry) => {
const { intersectionRatio, target } = entry;
const { id } = target;
if (isAlreadyImpressedItem(id) || !entry.isIntersecting) {
return;
}
if (intersectionRatio >= INTERSECTION_RATIO) {
changeStatusOnImpressing(target, id);
if (timeoutId) {
return;
}
timeoutId = setTimeout(() => {
changeStatusImpressed(target, id);
sendEvent();
timeoutId = null;
clearInterval(intervalId);
}, IMPRESSION_DURATION_THRESHOLD);
return;
}
clearTimeout(timeoutId);
timeoutId = null;
changeStatusNotOnImpressing(target, id);
});
};
};
const options = {
root: document.querySelector("#scrollArea"),
rootMargin: "10px",
threshold: [...Array(1000)].map((_, index) => index / 1000),
};
document.querySelectorAll(".list-item").forEach((item) => {
const observer = new IntersectionObserver(createCallback(), options);
observer.observe(item);
});