stylescape
Version:
Stylescape is a visual identity framework developed by Scape Agency.
73 lines • 2.73 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScrollSpyManager = void 0;
class ScrollSpyManager {
constructor(sections, navLinksSelector, containerId, thresholdOffset = 0.5) {
this.ticking = false;
this.sections = sections;
this.navLinks = document.querySelectorAll(navLinksSelector);
this.scrollContainer = containerId
? (document.getElementById(containerId) ?? window)
: window;
this.thresholdOffset = thresholdOffset;
this.bindScrollListener();
this.updateActiveLink();
}
bindScrollListener() {
const container = this.scrollContainer === window ? window : this.scrollContainer;
container.addEventListener("scroll", () => this.onScroll(), {
passive: true,
});
}
onScroll() {
if (!this.ticking) {
window.requestAnimationFrame(() => {
this.updateActiveLink();
this.ticking = false;
});
this.ticking = true;
}
}
updateActiveLink() {
if (!this.sections || this.sections.length === 0 || !this.navLinks)
return;
const scrollY = this.scrollContainer instanceof Window
? window.scrollY
: this.scrollContainer.scrollTop;
let activeId = null;
for (const section of this.sections) {
const id = section.getAttribute("id");
if (!id)
continue;
const top = section.offsetTop;
const height = section.offsetHeight;
const threshold = top - height * this.thresholdOffset;
if (scrollY >= threshold) {
activeId = id;
}
}
this.navLinks.forEach((link) => {
const targetId = link.getAttribute("href")?.replace("#", "");
const isActive = targetId === activeId;
link.classList.toggle("active", isActive);
let parent = link.parentElement;
while (parent && parent !== document.body) {
if (parent.tagName === "LI") {
parent.classList.remove("active");
}
parent = parent.parentElement;
}
if (isActive) {
let parent = link.parentElement;
while (parent && parent !== document.body) {
if (parent.tagName === "LI") {
parent.classList.add("active");
}
parent = parent.parentElement;
}
}
});
}
}
exports.ScrollSpyManager = ScrollSpyManager;
//# sourceMappingURL=ScrollSpyManager.js.map