-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScrollSpy.js
57 lines (50 loc) · 2.05 KB
/
ScrollSpy.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
// AJOOUTER DATA-SPY AUX ELEMENTS QUI DOIVENT ETRE ECOUTES
export default function scrollSpy () {
const ratio = 0.6,
spies = document.querySelectorAll("[data-spy]");
let observer = null;
const activate = function (e) {
const t = e.getAttribute("id"),
n = document.querySelector(`a[href="#${t}"]`);
if (null === n) return null;
const query = n.parentElement
if(!(query instanceof HTMLAnchorElement)) {
query.parentElement.querySelectorAll(".active").forEach((e) => e.classList.remove("active")), n.classList.add("active");
}
else {
query.querySelectorAll(".active").forEach((e) => e.classList.remove("active")), n.classList.add("active");
}
//n.parentElement.querySelectorAll(".active").forEach((e) => e.classList.remove("active")), n.classList.add("active");
},
callback = function (e) {
e.forEach(function (e) {
e.isIntersecting && activate(e.target);
});
},
observe = function (e) {
null !== observer && e.forEach((e) => observer.unobserve(e));
const t = Math.round(0.6 * window.innerHeight);
(observer = new IntersectionObserver(callback, { rootMargin: `-${window.innerHeight - t - 1}px 0px -${t}px 0px` })), spies.forEach((e) => observer.observe(e));
},
debounce = function (e, t) {
let n;
return function () {
let i = arguments,
r = this;
clearTimeout(n),
(n = setTimeout(function () {
e.apply(r, i);
}, t));
};
};
if (spies.length > 0) {
observe(spies);
let e = window.innerHeight;
window.addEventListener(
"resize",
debounce(function () {
window.innerHeight !== e && (observe(spies), (e = window.innerHeight));
}, 500)
);
}
}