Reputation: 109
I'm using an intersection observer to implement lazy loading on my images. If I only select one image with the querySelector, then it works. But for some reason I can't get querySelectorAll to work. I also tried getElementsByClassName and this is still not working. Any solutions??
html:
<section class="section" id="section--2">
<div class="photo__container--two">
<img
data-src="portrait/4-vertical.JPG"
alt=""
class="fade-in img-vertical-lazy"
/>
<img
data-src="portrait/5-vertical.JPG"
alt=""
class="fade-in img-vertical-lazy"
/>
<img
data-src="portrait/6-vertical.JPG"
alt=""
class="fade-in img-vertical-lazy"
/>
</div>
</section>
JavaScript:
const lazyImages = document.querySelectorAll('.img-vertical-lazy');
const lazyLoading = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
entry.target.src = entry.target.getAttribute('data-src');
lazyLoading.unobserve(entry.target)
});
});
lazyLoading.observe(lazyImages);
Upvotes: 1
Views: 110
Reputation: 1540
According to the InstersectionObserver docs, the observe
function receives a single node, not an array of nodes
You should rewrite the last line to this
lazyImages.forEach(image => lazyLoading.observe(image))
Upvotes: 2