I am trying to change the burger menu on my website everytime it sits on top of a section with a light background for visibility. I tried to use intersection observer, and the solution seems working, however it triggers too early on scroll, before actually the section intersects with the menu.
I am new to intersection observer, I tried to find something useful online but with no much luck.
const body = document.querySelector('body')
const sections = body.querySelectorAll('.change-menu')
const options = {
root: null,
threshold: 0,
rootMargin:'-40px 0px -80% 0px'
}
const observer = new IntersectionObserver((entries,observer) => {
entries.forEach(entry => {
if(entry.isIntersecting) {
document.querySelectorAll('.menu-item').forEach(bar => {
body.classList.add('black')
})
} else {
document.querySelectorAll('.menu-item').forEach(bar => {
body.classList.remove('black')
})
}
})
}, options)
sections.forEach(section => {
observer.observe(section)
})
Here is a jsfiddle of an example of my problem:
https://jsfiddle.net/bc7w8zt1/
Anyone can shed some light on it please?