-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
45 lines (39 loc) · 1.48 KB
/
script.js
File metadata and controls
45 lines (39 loc) · 1.48 KB
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
const header = document.querySelector("[data-header]");
const nav = document.querySelector("[data-nav]");
const navToggle = document.querySelector("[data-nav-toggle]");
const navLinks = Array.from(document.querySelectorAll(".site-nav a"));
const setHeaderState = () => {
header.classList.toggle("is-scrolled", window.scrollY > 18);
};
navToggle.addEventListener("click", () => {
const isOpen = nav.classList.toggle("is-open");
navToggle.setAttribute("aria-expanded", String(isOpen));
navToggle.setAttribute("aria-label", isOpen ? "Close navigation" : "Open navigation");
});
navLinks.forEach((link) => {
link.addEventListener("click", () => {
nav.classList.remove("is-open");
navToggle.setAttribute("aria-expanded", "false");
navToggle.setAttribute("aria-label", "Open navigation");
});
});
const sections = navLinks
.map((link) => {
const href = link.getAttribute("href");
return href && href.startsWith("#") ? document.querySelector(href) : null;
})
.filter(Boolean);
const sectionObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
navLinks.forEach((link) => {
link.classList.toggle("is-active", link.getAttribute("href") === `#${entry.target.id}`);
});
});
},
{ rootMargin: "-45% 0px -45% 0px", threshold: 0 }
);
sections.forEach((section) => sectionObserver.observe(section));
setHeaderState();
window.addEventListener("scroll", setHeaderState, { passive: true });