I am adding an sticky nav in my website using IntersectionObserver, when the isIntersecting passed from true to false, the website and nav starts flickering, in the background the isIntersecting start a loop between true and false causing this flickering behavior.
This is the JS code when I am applying the IntersectionObserver
const nav = document.querySelector(".nav-container");
const sticky = function (entries) {
const [entry] = entries;
console.log(entry);
if (!entry.isIntersecting) {
nav.classList.add("sticky");
} else {
nav.classList.remove("sticky");
}
};
const navObserver = new IntersectionObserver(sticky, {
root: null,
threshold: 0,
});
navObserver.observe(nav);
This is the CSS
.nav-container {
width: 100%;
height: 10vh;
position: relative;
border-bottom: 1px solid rgba(0, 0, 0, 0.5);
}
.nav-container.sticky {
position: fixed;
z-index: 5;
}
My expectation is to keep the nav fixed to the top once this one is set to isIntersecting=false, meaning that when I scroll down I want to keep visible the nav, I did it successfully in another project but not in this one.