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
{%- render 'loading-spinner',class:"loading__spinner" -%}
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);
});