javascriptjs-scrollto

Lazy loading conflicting with ScrollTo anchor to ID scroll - Stops halfway through the page


I have a scrollTo function on my page where when you click on a specific button you scroll to a section with a unique ID.

The problem is I am using lazy loading for the images on my website so, this will cause the ScrollTo to stop halfway through the page because of the images which are lazy-loaded.

After all, images are loaded and I click again on the button it works just fine.

My lazy load code:

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

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

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

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

    runLazy();

})();

My scroll to code:

(() => {
    document.querySelectorAll('a[href^="#"]').forEach((elem) => {
        elem.addEventListener('click', (e) => {
            e.preventDefault();
            let block = document.querySelector(elem.getAttribute('href')),
                offset = elem.dataset.offset
                    ? parseInt(elem.dataset.offset)
                    : 0,
                bodyOffset = document.body.getBoundingClientRect().top;
            window.scrollTo({
                top: block.getBoundingClientRect().top - bodyOffset + offset,
                behavior: 'smooth'
            });
        });
    });
})();

Is there a way to fix this?


Solution

  • This seems to be caused by the image size change event during lazy loading.

    So you could just set fixed height and width to the lazy load images, to skip this issue.

    Edit:

    Since fixed image size is not suitable, you can fix this with location.href = '#your-image-tag', plus window.scrollBy in image.onload event.

    key code:

    (() => {
      document.querySelectorAll('a[href^="#"]').forEach((elem) => {
          elem.addEventListener('click', (e) => {
              e.preventDefault();
              location.href = elem.getAttribute('href')
          });
      });
    })()
    
    image.target.onload = () => {
      image.target.classList.add("loaded");
    
      // TODO: check current image below or upper the target image
      window.scrollBy(0, image.target.clientHeight)
      // or window.scrollBy(0, 0 - image.target.clientHeight)
    }
    

    live demo: https://codesandbox.io/s/focused-field-2q3py?file=/src/index.js