infinite scrolling using the section rendering API on main-collection-product-grid Dawn theme

infinite scrolling using the section rendering API on main-collection-product-grid Dawn theme

waqarsheikh07
Shopify Partner
33 1 0

I implemented infinite scrolling using the section rendering API on "main-collection-product-grid". How can I fix the issue where it stops working after adding or removing a filter, and only works again after refreshing the page?

Here is script and html

 

 

 

 

<div id="infinite-scroll-loader" style="display: none;">    {%- render 'loading-spinner',class:"loading__spinner" -%}</div>
  document.addEventListener('DOMContentLoaded', function() {
  let currentPage = 1;
  const productGrid = document.getElementById('product-grid');
  const loader = document.getElementById('infinite-scroll-loader');
  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      loadMoreProducts();
    }
  }, { threshold: 1.0 });

  function loadMoreProducts() {
    currentPage++;
    loader.style.display = 'block';
    const url = `${window.location.pathname}?section_id=main-collection-product-grid&page=${currentPage}`;

    fetch(url)
      .then(response => response.text())
      .then((responseText) => {
        const parser = new DOMParser();
        const htmlDocument = parser.parseFromString(responseText, 'text/html');
        const newProducts = htmlDocument.getElementById('product-grid').innerHTML;
         // Check if the response contains "No products found"
        if (newProducts.includes("No products found")) {
          loader.style.display = 'none';
          observer.disconnect(); // Stop the observer
          return;
        }

        productGrid.insertAdjacentHTML('beforeend', newProducts);
        loader.style.display = 'none';

        // Re-observe the last product to continue infinite scrolling
        observer.observe(productGrid.lastElementChild);
      })
      .catch((error) => {
        console.error('Error loading more products:', error);
        loader.style.display = 'none';
      });
  }

  // Observe the last product initially
  observer.observe(productGrid.lastElementChild);
});

 

 

 

 

 

Waqar Sheikh | Shopify Partner | Ecommerce Consultant
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Click Accept as Solution  
 - Need further assistance? Visit www.waqarsheikh.com
Replies 0 (0)