How do I change selected main product image

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
  });
}

Hi @TrendBlend ,

Please paste the updated code.

function updateImageForSelectedVariant(selector) {
  const selectedVariantId = selector.value;

  const productMedia = document.querySelector('.product__media');
  const existingSpinner = productMedia.querySelector('.spinner');
  if (existingSpinner) existingSpinner.remove();

  const spinner = document.createElement('div');
  spinner.classList.add('spinner');
  productMedia.appendChild(spinner);

  const headerHeight = document.querySelector('header').offsetHeight || 0;
  const elementTop = productMedia.getBoundingClientRect().top + window.pageYOffset;
  const centerPosition = elementTop - (window.innerHeight / 2) + (productMedia.offsetHeight / 2);

  if (window.innerWidth <= 768) {
    window.scrollTo({
      top: centerPosition - headerHeight,
      behavior: 'smooth'
    });
  }

  getVariantById(selectedVariantId).then(variant => {
    const selectedImage = variant.featured_image ? variant.featured_image.src : null;
    const selectedMediaId = variant.featured_image ? variant.featured_image.id : null;

    if (selectedImage && selectedMediaId) {
      // Find the correct image slide or thumbnail
      const allImages = document.querySelectorAll('[data-media-id]'); // Shopify adds data-media-id to image wrappers

      let matchedImageElement = null;
      allImages.forEach(imgWrapper => {
        if (imgWrapper.getAttribute('data-media-id') === String(selectedMediaId)) {
          matchedImageElement = imgWrapper;
        }
      });

      if (matchedImageElement) {
        matchedImageElement.scrollIntoView({ behavior: 'smooth', block: 'center' });

        // Optionally trigger click if using a thumbnail-based slider
        const imgInside = matchedImageElement.querySelector('img');
        if (imgInside) imgInside.click();
      } else {
        console.warn("Matching image not found for variant ID:", selectedVariantId);
      }

      spinner.remove();
    }
  }).catch(error => {
    console.error("Error updating image:", error);
    spinner.remove();
  });
}

Hello @websensepro , Thanks for your message!
I updated the code to your code above, but the product image now does not changing when changing variants in the custom bundle anymore.
Note how the image shows 1x1M - Type A (EU) and the variant selector shows 2x2M - Type A (EU)