-
Notifications
You must be signed in to change notification settings - Fork 0
/
in-view.js
49 lines (42 loc) · 977 Bytes
/
in-view.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
// @ts-self-types="./in-view.d.ts"
class InView extends HTMLElement {
static tagName = "in-view";
observer;
static register(
tagName = InView.tagName,
registry = globalThis.customElements,
) {
registry?.define(tagName, InView);
}
get options() {
return {
rootMargin: this.getAttribute("data-rootMargin") || "0px",
threshold: Number.parseFloat(this.getAttribute("data-threshold") || "1"),
};
}
get templateEl() {
return this.querySelector("template");
}
connectedCallback() {
this.observer = new IntersectionObserver(
this.callback.bind(this),
this.options,
);
this.observer.observe(this);
}
disconnectedCallback() {
this.observer?.unobserve(this);
}
callback(entries, observer) {
for (const entry of entries) {
if (entry.isIntersecting) {
if (this.templateEl) {
this.appendChild(this.templateEl.content?.cloneNode(true));
}
observer.unobserve(this);
}
}
}
}
InView.register();
export { InView };