'intersection oberserver used with a loop through all the elements ends in error
I want to show some cards on scroll and for that purpose I chose to use an intersection observer.
But I ended up with:
Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.
Here is a sample code of what I am trying to do =>
HTML:
<div class="card">demo</div>
<div class="card">demo</div>
<div class="card">demo</div>
<div class="card">demo</div>
JS:
const cards = document.querySelectorAll(".card");
const options = {
root: null,
threshold: 0.2
}
const observer = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add("appear-on-scroll");
observer.unobserve(entry.target);
} else {
return;
}
});
}, options);
observer.observe(cards);
Solution 1:[1]
The answer is to loop through the array that consists of nodes twice like:
const cards = document.querySelectorAll(".card");
const options = {
root: null,
threshold: 0.2
}
const observer = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add("appear-on-scroll");
observer.unobserve(entry.target);
} else {
return;
}
});
}, options);
// second loop through
cards.forEach(card => observer.observe(card));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sina_byn |
