How to reintialize Product media gallery functionality on Shopify Dawn theme when the gallery is reloaded via AJAX

I'm reloading product info and gallery parts via Ajax on product page. After the reload I reintialize some custom JS that I've written and it works but I'm having trouble to reintialize standart gallery/thumnail functionality, specifically on desktop the thumbnails when clicked do not change the image (on mobile Next/Previous slider buttons work). This is the attempt which is not working: document.addEventListener("DOMContentLoaded", function () { // Function to bind event listeners to case type links function bindCaseTypeLinks() { document.querySelectorAll('.case-types a').forEach(function (link) { link.addEventListener('click', function (event) { event.preventDefault(); // Prevent default page navigation const productUrl = this.href; showLoadingSpinner(); // Fetch the new product page content via AJAX fetch(productUrl) .then(response => response.text()) .then(html => { const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); // Replace product info section with the new content const newProductInfo = doc.querySelector('#ProductInfo-template--23236676976943__main'); const newGalleryInfo = doc.querySelector('#MediaGallery-template--23236676976943__main'); if (newProductInfo) { document.querySelector('#ProductInfo-template--23236676976943__main').innerHTML = newProductInfo.innerHTML; document.querySelector('#MediaGallery-template--23236676976943__main').innerHTML = newGalleryInfo.innerHTML; // Reinitialize any JS (sliders, variant pickers, etc.) bindCaseTypeLinks(); // Rebind links to work for the new product content hideLoadingSpinner(); initializePhoneModelOverlayForProductPage(); if (newGalleryInfo) { // Safely replace the media gallery content const existingMediaGallery = document.querySelector('#MediaGallery-template--23236676976943__main'); if (existingMediaGallery) { existingMediaGallery.innerHTML = newGalleryInfo.innerHTML; } } // Reinitialize custom elements if necessary const galleries = document.querySelectorAll('media-gallery'); galleries.forEach(gallery => { if (typeof gallery.connectedCallback === 'function') { gallery.connectedCallback(); // Explicitly trigger the connectedCallback to reinitialize the element } }); // Reinitialize Shopify sections and components document.querySelectorAll('[data-section-type="product"]').forEach(function(section) { Shopify.theme.sections.load(section); }); } }) .catch(error => { console.error('Error fetching product page:', error); }); }); }); } // Bind event listeners initially bindCaseTypeLinks(); });

Comment (0)

You’ll be in good company