'Intersection Observer not selecting a target at some point
The code below adds class to elements when they are scrolled into view which currently works but I'm struggling to achieve the following.
- When target is within the top 20% of the root, it should be have the class added.
- If 2 elements are intersecting at the same time, then the bottom element is selected.
How to spot the current issue:
If you scroll slowly, you discover that at some point no item is selected.
window.addEventListener("load", (event) => {
const parent = document.getElementById('parent');
for (let i = 1; i <= 10; i++) {
const child = document.createElement('div');
child.id = String(i);
child.innerHTML = child.id;
child.classList.add('item')
parent.appendChild(child);
}
const options = {
root: parent,
rootMargin: '-20% 0% -80% 0%',
threshold: [0, 1]
}
const callback = function(entries) {
let entry = entries[0];
if (entry.isIntersecting && entry.intersectionRatio >= 0) {
entry.target.classList.add("active");
} else {
entry.target.classList.remove("active");
}
}
const observer = new IntersectionObserver(callback, options)
const targets = document.getElementsByClassName('item');
for (let i = 0; i < targets.length; i++) {
observer.observe(targets[i]);
}
}, false);
body {
overflow-y: hidden;
}
.wrapper {
background: #E7ECF5;
border: 2px solid #02E4FF;
padding: 2em;
}
#parent {
height: 350px;
overflow-y: scroll;
}
div {
background: #fff;
border: 2px solid grey;
margin-bottom: 20px;
padding: 2em;
}
[class*='active'] {
opacity: 1;
border: 3px solid red;
}
<div class="wrapper">
<div id="parent"></div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
