-1

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?

1

1 Answer 1

0

Use entry.target.classList.contains('lazy') instead of entry.target.className === 'lazy'

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.