astro-ghostcms/.pnpm-store/v3/files/bd/3aae684c46b1a43e69d26e95e2a...

59 lines
1.4 KiB
Plaintext

---
interface Props {
scrollY?: number;
activeClass?: string;
defaultClass?: string;
class?: string;
}
const {
scrollY = 100,
defaultClass = "",
activeClass = "",
class: className = "",
} = Astro.props;
---
<header class:list={["astronav-sticky-header", className, defaultClass]}>
<slot />
</header>
<script define:vars={{ scrollY, defaultClass, activeClass }}>
let scrollPos = 0;
let ticking = false;
function OnScroll(scrollPos) {
const headers = document.querySelectorAll(".astronav-sticky-header");
const classArray = activeClass.split(" ");
const replaceArray = defaultClass.split(" ");
headers.forEach((header) => {
if (scrollPos > scrollY) {
header.classList.remove(...replaceArray);
header.classList.add("is-active", ...classArray);
header.setAttribute("active", "");
}
//reduce the scrollY to avoid flickering when scrolling up
if (scrollPos < Math.max(scrollY - 20, 0)) {
header.classList.remove("is-active", ...classArray);
header.classList.add(...replaceArray);
header.removeAttribute("active");
}
});
}
// Scroll event throttling as per MDN
// https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event
document.addEventListener("scroll", (event) => {
scrollPos = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(() => {
OnScroll(scrollPos);
ticking = false;
});
ticking = true;
}
});
</script>