I trust that you found this blog post to be enjoyable. If you are interested in having my team handle your eCommerce setup and marketing for you, Contact Us Click here.

How to Add Swatches on Collection and Related Products in Dawn Theme

How to Add Swatches on Collection and Related Products in Dawn Theme

If you’re running a Shopify store with the Dawn theme, you can add swatches to your Collections page as well as the Related Products page. It can make the shopping experience even smoother for your clients. Your clients won't have to click into every product. Instead, they can see colours or style options right on the product card. Here's how you set it up:

Steps to Add Swatches

Open the Theme Code Editor

  • Visit the Shopify Admin console.

  • Click on Online Store and navigate to Themes.

  • Click on the Edit Code option

Create a Swatch Snippet

  • Open the Snippets folder.

  • Click on the “Add a new snippet” option.

  • Change the name to :

card-variant-swatch-custom.liquid


 

  • To do this, right-click on the Snippet folder and select the “Create Snippet file name” option.

  • Paste the following code inside the text box:

{% assign base_store_files_url = '//' | append: shop.permanent_domain | append: '/cdn/shop/files/' %}
{% assign product_form_id = 'product-form-' | append: product.id %}

{% liquid
  assign swatchStyle = 'round'
    assign swatchSize = 50
%}


{% for value in option.values %}
  {% assign variant_image_url = nil %}
  {% assign variant_id = nil %}
  {% assign option_disabled = true %}
  {% assign first_match_found = false %}

  {% for variant in product.variants %}
    {% if first_match_found == false %}
      {% case option.position %}
        {% when 1 %}
          {% if variant.option1 == value %}
            {% assign variant_image_url = variant.featured_media | img_url: '300x300' %}
            {% assign variant_id = variant.id %}
            {% if lazy_load_all_variants %}
              <!-- Preload image -->
              <img 
                src="{{ variant_image_url }}" 
                alt="{{ variant.title }}" 
                style="display: none;" 
                loading="lazy"
                data-variant-id="{{ variant.id }}"
                width="{{ variant.featured_media.width }}"
                height="{{ variant.featured_media.height }}">
            {% endif %}
            {% if variant.available %}
              {% assign option_disabled = false %}
            {% endif %}
            {% assign first_match_found = true %}
          {% endif %}
        {% when 2 %}
          {% if variant.option2 == value and variant.option1 == product.selected_or_first_available_variant.option1 %}
            {% assign variant_image_url = variant.featured_media | img_url: '300x300' %}
            {% assign variant_id = variant.id %}
            {% if lazy_load_all_variants %}
              <!-- Preload image -->
              <img 
                src="{{ variant_image_url }}" 
                alt="{{ variant.title }}" 
                style="display: none;" 
                loading="lazy"
                data-variant-id="{{ variant.id }}"
                width="{{ variant.featured_media.width }}"
                height="{{ variant.featured_media.height }}">
            {% endif %}
            {% if variant.available %}
              {% assign option_disabled = false %}
            {% endif %}
            {% assign first_match_found = true %}
          {% endif %}
        {% when 3 %}
          {% if variant.option3 == value and variant.option1 == product.selected_or_first_available_variant.option1 and variant.option2 == product.selected_or_first_available_variant.option2 %}
            {% assign variant_image_url = variant.featured_media | img_url: '300x300' %}
            {% assign variant_id = variant.id %}
            {% if lazy_load_all_variants %}
              <!-- Preload image -->
              <img 
                src="{{ variant_image_url }}" 
                alt="{{ variant.title }}" 
                style="display: none;" 
                loading="lazy"
                data-variant-id="{{ variant.id }}"
                width="{{ variant.featured_media.width }}"
                height="{{ variant.featured_media.height }}">
            {% endif %}           
            {% if variant.available %}
              {% assign option_disabled = false %}
            {% endif %}
            {% assign first_match_found = true %}
          {% endif %}
      {% endcase %}
    {% endif %}

    {% if variant_image_url %}
      {% for item in variant_images_data %}
        {% if item.variant_value == value %}
{% assign variant_filename = item.variant_swatch %}
            {% unless variant_filename == blank %}
              {% assign variant_image_url = base_store_files_url | append: variant_filename %}
            {% endunless %}
          {% break %}
        {% endif %}
      {% endfor %}
    {% endif %}
  {% endfor %}

  <div class="collection-product-card__swatch">
    <input 
      type="radio"
      id="collection-{{ section.id }}-{{ product.id }}-{{ option.position }}-{{ forloop.index0 }}" 
      name="collection-{{ section.id }}-{{ product.id }}-{{ option.name }}" 
      value="{{ value | escape }}" 
      form="{{ product_form_id }}" 
      data-section-id="{{ section.id }}"
      data-product-id="{{ product.id }}" 
      data-variant-id="{{ variant_id }}"
      data-image-url="{{ variant_image_url }}"
      {% if option.selected_value == value %}
        checked
      {% endif %}
      {% if option_disabled %}
        class="disabled"
      {% endif %}
    >
   {% unless variant_image_url contains 'no-image' %}
  <label 
    class="color-swatch round" 
    style="background:url('{{ variant_image_url }}');" 
    for="collection-{{ section.id }}-{{ product.id }}-{{ option.position }}-{{ forloop.index0 }}">
      <span class="visually-hidden">
        {{ 'products.product.variant_sold_out_or_unavailable' | t }}
      </span>
  </label>
{% endunless %}

  </div>
{% endfor %}


This will help you create a Swatch Snippet.

Add JavaScript

  • Open the Assets folder.

  • Click on the “Add a new asset file” option. Name the file:

card-product-variant-selection-custom.js



  • Open the new file and paste the following code inside the text box:

(function () {
const RESPONSIVE_WIDTHS = [165, 360, 533, 720, 940, 1000];

function absUrl(u) {
return u.startsWith("//") ? window.location.protocol + u : u;
}

function buildSrcset(absoluteUrl) {
const base = absUrl(absoluteUrl);
return RESPONSIVE_WIDTHS.map(w => {
const u = new URL(base);
u.searchParams.set("width", w);
return u.toString() + ` ${w}w`;
}).join(", ");
}

function updateCardImageFromLabel(labelEl) {

const inputId = labelEl.getAttribute("for");
const inputEl = inputId ? document.getElementById(inputId) : labelEl.previousElementSibling;
if (!inputEl) return console.warn("No input found for label:", labelEl);

const imgUrl = inputEl.dataset.imageUrl; // data-image-url
if (!imgUrl) return console.warn("No data-image-url on input:", inputEl);


const card = labelEl.closest(".card-wrapper, .card, .grid__item");
const mainImg = card && card.querySelector(".card__media img");
if (!mainImg) return console.warn("Main image not found for card:", card);

// src + srcset update
const abs = absUrl(imgUrl);
try {
const u = new URL(abs);
// ek reasonable default src width
u.searchParams.set("width", 533);
mainImg.src = u.toString();
mainImg.srcset = buildSrcset(abs);

// alt ko color value se update kar do (optional)
const color = inputEl.value || inputEl.getAttribute("value");
if (color) mainImg.alt = color;

// visual feedback (optional fade)
// mainImg.style.opacity = "0.85";
// setTimeout(() => (mainImg.style.opacity = ""), 120);
} catch (e) {
// agar URL parse na ho to at least src set kar do
mainImg.src = abs;
mainImg.removeAttribute("srcset");
}
}

// Event delegation: sab labels ke clicks yahan pakde jayenge
document.addEventListener("click", function (e) {
const label = e.target.closest("label.color-swatch");
if (!label) return;

// first-time class add (in case not present)
label.classList.add("round");
updateCardImageFromLabel(label);
});

// Page load par existing labels ko shape class de do (optional)
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll("label.color-swatch").forEach(l => l.classList.add("round"));
});

// shopify:section:load ki zaroorat nahi — delegation se sab cover ho jayega
})();


Include the JavaScript in Theme

  • Open the Layout folder and then open the theme.liquid option.

  • Add this line before the closing </body> tag:

<script src="{{ 'card-product-variant-selection-custom.js' | asset_url }}" defer="defer"></script>


Define Swatch Options

  • Again open the Snippets folder and then open the card-product.liquid file.

  • Add the following line at the top of the file:

{% assign variant_option_name = "Color" %}
{% assign lazy_load_all_variants = false %}


Wrap Product Card

  • While you have the card-product.liquid file open, locate the following lines:

<div class="card-wrapper product-card-wrapper underline-links-hover">

 

  • Wrap it with the following DIV:



<div class="card-product-custom-div" data-section-id="{{ section.id }}" data-lazy-load-all-variants="{{ lazy_load_all_variants }}">
<div class="card-wrapper product-card-wrapper underline-links-hover">


Render the Swatches

  • Before you close the </div> of the product card, insert the following rendering code that calls your snippet and displays swatches:

</div> <!-- card-wrapper -->


Save and Test

  • Open the Collections page. Or, you can also open a product page with related products.

  • You should now see clickable swatches under each card. Select one and it will update the product image instantly.

Conclusion

These before mentioned steps will help you add color swatches to your Shopify store on the Dawn theme. This will ensure that your shoppers are able to browse colors and variants directly on collection pages and related products. It makes the shopping experience faster and more soothable. This is a small change, but you can considerably improve your engagement and sales through this step.

Frequently Asked Questions

Q1. Do I also need coding knowledge to add switches to the theme?

A. Basic knowledge of Shopify theme editing is enough. You just need to copy-paste the snippets, JavaScript and Liquid code given in the guide.

Q2. Can I add switches for all product types or just colors?

A. While switches are usually used for colors, you can also resize them, set the size of the font or any other option by changing the code.

Q3. Will this customization only work on the collection page?

A. No, it will also work on the related products section (product suggestions) when you add the swatch snippet to the product card.

Q4. Can a customer see the change in the product image by clicking on the switch?

A. Yes, the product image updates instantly from the switch picture page, allowing customers to take advantage of the different variations.

Q5. Will this customization break when you update the theme?

A. Theme customizations can overwrite custom code. This is safe as long as you reapply your snippet-supported posts and theme updates in a timely manner.

Back to blog

Are you interested in boosting your sales orders?

"PTI WebTech has a proven strategy to boost your sales. Contact us to learn more."

Conact Us

Newsletter

Subscribe our Newsletter for our blog posts and our new updates. Let's stay updated!

Our Latest Post