Add image swatches on Dawn theme 15.2.0 with coding

HI,

I try to add image swatches on my product page. I know about a method where you can connect image/color swatches with meta field connection. But is there an easier way to add it with coding where it will automatic pick the picture selected on the variant?

Hi @Latelier539 I was able to implement something like this on the dawn theme and this would work on any free theme provided by Shopify. Please check reference site below of one of my client.

Site: www.kpsclothing.in

If this is something you are looking for, please reach out via mail for a convenient conversation and collaboration.

Best

Shadab

Hi @Latelier539 ,

To add image swatches to your product page on the Dawn theme and have them automatically display the selected variant’s image, here’s a streamlined approach using Liquid and JavaScript. This avoids needing to use metafields:

Steps to Implement Automatic Image Swatches1. Access Theme Code:

  • Go to Online Store > Themes > Edit Code in your Shopify admin.
  1. Edit the Product Template:

    • Open Sections/product-template.liquid or a similarly named file that controls product displays.
  2. Add Image Swatches:

    • Loop through the product variants to create clickable image swatches. Use each variant’s image by accessing {{ variant.featured_image.src }}.
    • Here’s a basic Liquid code snippet to add under the product images section:
{% for variant in product.variants %}
  
{% endfor %}
  1. JavaScript for Swatch Selection:

    • Use JavaScript to detect clicks on each swatch and update the main product image accordingly.
    • Add this script in product-template.liquid or the theme’s JavaScript file to handle swatch interactions:
document.querySelectorAll('.variant-swatch').forEach(swatch => {
  swatch.addEventListener('click', function() {
    const variantId = this.getAttribute('data-variant-id');
    const selectedVariantImage = this.getAttribute('src');
    document.querySelector('.main-product-image').src=selectedVariantImage;
  });
});
  • Ensure you’ve set the class=“main-product-image” on the main product image in your template so this script updates it correctly.

This method lets the product image update dynamically based on the selected variant without requiring metafield setup, making it simpler and more responsive for customers.

For further optimization, SEOPro can assist in ensuring your image alt text aligns with SEO best practices, as well as audit overall product page SEO to improve your store’s visibility.

Full disclosure: We are the developers of SEOPro. If you have questions, feel free to reach out at support@seo-pro.app.

Phil
SEOPro Developer

Thank you for the response, sadly i couldn’t get it to work.
I couldn’t find the locations where i have to add the code. i tried some but it didn’t work sadly.