I have an issue with my Javascript code and I hope somebody can help me with this.
I created an lazy load function for images.
<script type="text/javascript">
let options = {
root: null,
rootMargin: '0px',
threshold: 0.75
};
let callback = (entries, observer) => {
entries.forEach(entry => {
if(entry.isIntersecting && entry.target.className === 'lazy'){
let imageUrl = entry.target.getAttribute("data-src");
if(imageUrl){
entry.target.src = imageUrl;
}
}
});
}
let observer = new IntersectionObserver(callback, options);
lazy = document.querySelectorAll("img.lazy");
for(i=0; i < lazy.length; i++){
observer.observe(lazy[i]);
}
</script>
Works for this element
<img data-src="https://www.example.com/image.jpg" src="" class="lazy"/>
Does not work for this element
<img data-src="https://www.example.com/image.jpg" src="" class="test lazy"/>
The differents between these both elements are one has an extra class test
How can I fix this issue in my Javascript code?
Use entry.target.classList.contains('lazy') instead of entry.target.className === 'lazy'