I will try to explain what I am trying to do here. I have created 5 sections and each has a min-height of 100vh to create a fullscreen effect when you scroll down. Each section has a unique ID.
Now, I have a fixed CSS navbar that is set to the top. Inside the navbar, I have a logo and I would like to add a class to the logo IF the IO detects if a specific section with a unique ID is in the viewport.
The problem I am facing is that the IO will work with a threshold set to 0.99 or 1.
Immediately after the FIXED navbar enters another section from the top the class should apply.
This works… but I also want to remove the same class if you scroll back like to the previous section.
The problem is… the class will only be removed if you reach the TOP of the previous section and not from the bottom.
Depending on if you scroll from top or from bottom to the top. The IO really confuses me. Also if you scroll too fast will cause this not to work.
The thing that I am trying to do is that I have 2 sections with a white background and 2 with a pink background.
The logo has a white text color but should be for instance black if you enter the white section and if you go back to white it should be pink. If that make sense? Something like a scroll spy but only the logo should have a class to it.
My code:
section {
min-height: 100vh;
position: relative;
display: flex;
align-items: center;
justify-items: center;
}
#intro { background: cyan; }
#about { background: magenta; }
#services { background: yellow; }
#contact { background: lime; }
.fixed-bar {
top: 0;
position: fixed;
width: 100%;
height: 4em;
background: #222;
z-index: 1;
}
<div class="fixed-bar">
<h2 class="navigation__brand">MY LOGO</h2>
</div>
<section id="diensten">Content</section>
<section id="werkwijze">Content</section>
<section id="team">Content</section>
<section id="contact">Content</section>
(() => {
const sections = document.querySelectorAll('section');
const navBrand = document.querySelector('.navigation__brand');
const changeNav = (entries) => {
navBrand.style.border = '0';
entries.forEach((entry) => {
const id = entry.target.getAttribute('id');
const currentY = entry.boundingClientRect.y;
const currentRatio = entry.intersectionRatio;
const isIntersecting = entry.isIntersecting;
if (currentY <= 0) {
if (isIntersecting && currentRatio) {
if (id === 'team') {
navBrand.style.border = '2px solid red';
}
if (id === 'diensten') {
navBrand.style.border = '2px solid green';
}
}
}
});
};
const options = {
threshold: [0.01, 0.99],
rootMargin: '0px 100px 0px 0px'
};
const observer = new IntersectionObserver(changeNav, options);
sections.forEach((section) => {
observer.observe(section);
});
})();
Hopefully, someone can help me out. Thanks in advance.