My IntersectionObserver
uses a forEach
method to call some functions if a condition is met per each item of 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 logic I can use in the onObserve
callback for when this condition is not met for any of the array items? As in:
function onObserve(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const { id } = entry.target
removeHighlight(selectedId)
addHighlight(id)
selectedId = id
}
})
// otherwise, if none of the items meet the condition
// do something else
}
2
Answers
You can check if none of the items meet the condition by using the ‘every‘ method on the array of entries. The every method tests whether all elements in the array pass the provided function. If any entry is not intersecting, you can execute a specific logic. Here’s how you can modify your onObserve function:
In the example above, the ‘some’ method is used to check if at least one entry is intersecting. If isAnyIntersecting is true, it means at least one item meets the condition, and the logic inside the if block is executed. If it’s false, the logic inside the else block is executed, indicating that none of the items meet the condition.
You can try something like this: