Galanthus
Galanthus

Reputation: 2290

Eslint - 'observer' was used before it was defined?

I am trying to solve my order issue I am getting an Eslint error where "observer" was used before it was defined. But when I replace the observer above the onInterSection function I get onIntersection was used before it was defined.

(() => {
    let images = [...document.querySelectorAll('[data-src]')];

    const settings = {
        rootMargin: '50px 0px',
        threshold: 0.01
    };

    const onIntersection = (imageEntites) => {
        imageEntites.forEach((image) => {
            if (image.isIntersecting) {
                observer.unobserve(image.target);
                image.target.src = image.target.dataset.src;
                image.target.onload = () =>
                    image.target.classList.add('loaded');
            }
        });
    };

    let observer = new IntersectionObserver(onIntersection, settings);

    images.forEach((image) => observer.observe(image));
})();

Upvotes: 0

Views: 211

Answers (1)

cloned
cloned

Reputation: 6742

You could try and write it like this:


    let observer = new IntersectionObserver((imageEntites) => {
        imageEntites.forEach((image) => {
            if (image.isIntersecting) {
                observer.unobserve(image.target);
                image.target.src = image.target.dataset.src;
                image.target.onload = () =>
                    image.target.classList.add('loaded');
            }
        });
    };, settings);

Upvotes: 1

Related Questions