All things Shopify and commerce
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);
});
Hey Community! As we jump into 2025, we want to give a big shout-out to all of you wh...
By JasonH Jan 7, 2025Hey Community! As the holiday season unfolds, we want to extend heartfelt thanks to a...
By JasonH Dec 6, 2024Dropshipping, a high-growth, $226 billion-dollar industry, remains a highly dynamic bus...
By JasonH Nov 27, 2024