My IntersectionObserver
utilizes a forEach
method to invoke certain functions when a condition is met for each item in an array:
const sections = document.querySelectorAll("section")
function removeHighlight(id) {
someElementArray[id].classList.remove('highlight')
}
function addHighlight(id) {
someElementArray[id].classList.add('highlight')
}
function onObserve(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const { id } = entry.target
removeHighlight(selectedId)
addHighlight(id)
selectedId = id
}
})
}
const observer = new IntersectionObserver(onObserve, options)
sections.forEach((section) => {
observer.observe(section)
})
Is there a way to implement logic in the onObserve
callback for when none of the array items meet the condition? For example:
function onObserve(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const { id } = entry.target
removeHighlight(selectedId)
addHighlight(id)
selectedId = id
}
})
// If none of the items meet the condition
// Perform an alternate action
}