0

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))
    }
}
flks
  • 610
  • 10
  • 28
  • It seems that it only doesn't work when you don't scroll from below the header, but from the middle of the header. Try maybe setting an array of `threshold`s and then based on `entry.intersectionRatio` decide when to change the brightness. It might be even enough to change `threshold` to for example `0.5`. – touchmarine Nov 08 '20 at 15:50
  • Interesting. I tried `threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]` but that doesn't seem to fix the issue unfortunately – flks Nov 08 '20 at 16:59
  • Did you modify `entry.intersectionRatio > 0` after you changed the `threshold`. Maybe try `entry.intersectionRatio > 0.5` and see if it is better - if it is, then you can fine tune in. You can even detect scrolling direction with IntersectionObserver if you want more precise behaviour. – touchmarine Nov 09 '20 at 16:46

0 Answers0