I adapted the code from this question to my situation where I need to change the "brightness" of my header links depending of the section's background scrolling under.
It works pretty well but sometimes it feels like it's missing the detection as pictured in this video:
https://i.stack.imgur.com/hezHQ.jpg
// Change brightness
const changeBrightness = brightness => {
header.classList.remove('is-light', 'is-dark')
header.classList.add(brightness === 'dark' ? 'is-light' : 'is-dark')
}
// Change header brightness depending on which area is scrolling under
const headerScrollDetect = () => {
if (typeof IntersectionObserver !== 'undefined') {
const { top, height } = header.getBoundingClientRect()
const options = {
rootMargin: `-${top}px 0px -${window.innerHeight - top - height}px 0px`,
threshold: 0
}
const sections = document.querySelectorAll('[data-brightness]')
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
entry.intersectionRatio > 0 && changeBrightness(entry.target.dataset.brightness)
})
}, options)
// Detect scroll on each sections
sections.forEach(section => observer.observe(section))
}
}