I'm working on implementing a sticky nav using the intersection observer API. The sticky class is added when the header element is not intersecting. However, when I scroll to the end of the header and to the next section, right at that threshold, the sticky class is added and removed repeatedly dozens of times per second, causing an intense flickering. It only happens when I have a declared height (100vh) but when I changed height to "auto," it didn't flicker. Why is this happening?
HTML:
<header>
<nav class="navigation">
<a href="#"><img src="img/logo@2x.png" alt="ActiveBox logo" class="logo" /></a>
<ul class="main-nav nav__links">
<li><a href="#section--1" class="nav__link">Features</a></li>
<li><a href="#section--2" class="nav__link">Works</a></li>
<li><a href="#section--3" class="nav__link">Our Team</a></li>
<li><a href="#section--4" class="nav__link">Testimonials</a></li>
<li><a href="#section--5" class="nav__link">Download</a></li>
</ul>
</nav>
<div class="hero-text-box">
<h1>Your Favorite One Page Multi Purpose Template</h1>
<h2>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et.
</h2>
<a class="btn-full" href="#">Find Out More</a>
</div>
</header>
Not sure if the Javascript code will be helpful here, because it seems like an issue with CSS, but adding that here:
const nav = document.querySelector("nav");
const header = document.querySelector("header");
const navHeight = nav.getBoundingClientRect().height;
const observerCallback = function (entries, observer) {
const [entry] = entries;
if (!entry.isIntersecting) nav.classList.add("isSticky");
if (entry.isIntersecting) nav.classList.remove("isSticky");
};
const observerOptions = {
root: null,
threshold: 0.1,
rootMargin: `-${navHeight}px`,
};
const headerObserver = new IntersectionObserver(
observerCallback,
observerOptions
);
headerObserver.observe(header);