My question here is two-part. But all relative to understanding more about how the intersection observer works.
I get all my 'sections', loop through and apply the observer to each one. My goal is if the section is intersecting, I want to apply a style, and for the ones that are not intersecting I don't want the style applied. on page load, all my sections have the border and are not toggling as I would expect them to. Also, in my console.log(entry) the entry seems to log before I actually intersect with the section.
ex: I am scrolling up and am still clearly in the border of "section 3" but the log for "section 2" has already shown up.
Some help with a general understanding and some possible solutions would be amazing.
let allSections = document.querySelectorAll('section')
const options = {
root: null,
threshold: 0,
rootMargin: '0px'
}
const observer = new IntersectionObserver(function
(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('ENTRY', entry.target)
entry.target.style.border = '1px solid red'
} else {
entry.target.style.border = '1px solid transparent'
}
})
}, options)
allSections.forEach(section => {
observer.observe(section)
})
It is because of your options object, the threshold need to be greater than 0 if you wanna see your animation happens.
threshold: 1 means entry.isIntersecting is true when 100% of the element is in the viewport.
threshold: 0.3 means entry.isIntersecting is true when 30% of the element is in the viewport, etc.
const options = {
root: null,
threshold: 1,
rootMargin: '0px'
}
If you wanna know more about it, you can read on MDN documentation here.