Hello, for my product page I got my thumbnail slider and product image slider. When the variant is changed in my custom bundle, I want to select an image from the variant ID from a product from the list.
I currently have this code, but this changes the first image from the list instead of selecting the correct image. URL: Glow Curtain: 400 LED Lights for a Magical Ambiance – InteriorGlows
// Function to update image when variant selector changes
function updateImageForSelectedVariant(selector) {
const selectedVariantId = selector.value;
const productMedia = document.querySelector('.product__media');
const existingSpinner = productMedia.querySelector('.spinner'); // Check if there's already a spinner
if (existingSpinner) {
existingSpinner.remove(); // Remove the existing spinner if present
}
const spinner = document.createElement('div');
spinner.classList.add('spinner'); // Add the spinner class for styling
productMedia.appendChild(spinner);
// Get the height of the header (assuming it's a fixed header)
const headerHeight = document.querySelector('header').offsetHeight || 0;
// Calculate the position to scroll to, centered in the viewport
const elementTop = productMedia.getBoundingClientRect().top + window.pageYOffset;
const centerPosition = elementTop - (window.innerHeight / 2) + (productMedia.offsetHeight / 2);
// Scroll to the calculated center position
// Check if the device width is less than or equal to 768px (common for phones)
if (window.innerWidth <= 768) {
window.scrollTo({
top: centerPosition - headerHeight, // Adjust for header
behavior: 'smooth'
});
}
getVariantById(selectedVariantId).then(variant => {
const selectedImage = variant.featured_image ? variant.featured_image.src : null;
if (selectedImage) {
const productImageElement = document.querySelector('.product__media img'); // Ensure this selector is correct
if (productImageElement) {
const updatedImagesrc=selectedImage + "?t=" + new Date().getTime(); // Cache busting
// Temporarily hide the image while updating
productImageElement.style.visibility = 'hidden';
// Update the image source
productImageElement.src=updatedImageSrc;
productImageElement.srcset = updatedImageSrc; // Update srcset as well
// Wait for the new image to load
productImageElement.onload = function() {
// Hide the spinner once the image has loaded
spinner.remove();
// Show the image again after it's loaded
productImageElement.style.visibility = 'visible';
};
productImageElement.onerror = function() {
console.error('Error loading image');
spinner.remove(); // Remove the spinner in case of error
};
}
}
}).catch(error => {
console.error("Error updating image:", error);
spinner.remove(); // Remove the spinner in case of an error
});
}
