Grouping images with color variants - Debut theme

For older themes, try the article for the Launchpad theme

This article will show you how to group variant images by color on product pages in the Debut Shopify theme. Only the images related to the selected variant will be displayed. 

The code may need to be adjusted to suit the theme you are working on. 

Take a look at the demo to see how it should end up functioning: https://themetweaks.ca/products/anson-chair-variant-images?variant=1618534793226

To get started, you need associate each product image with a variant.

For example: I only want the yellow chair image, and the yellow pillow image to show as thumbnails when "Option 2" is selected. 

I will be using alt tags to associate each image.

Apply the matching variant option title to each image:

 

We will begin our changes in the product-template.liquid section file. Find the code for the image thumbnails, it should look like this:

<ul class="grid grid--uniform product-single__thumbnails product-single__thumbnails-{{ section.id }}">

Above this line add:

{% assign featured_alt = product.selected_or_first_available_variant.option1 %}
         
{% for option in product.options  %}
  {% if option == "Color" %}
    {% assign color_index = forloop.index0 %}
  {% endif %}      	
{% endfor %}
            
{% assign color_values = product.options_with_values[color_index].values %}

{% for color in color_values %}

Next find the line of code that looks like:

{% for image in product.images %}

Directly after that add:

{% if color == image.alt %}

Find the closing for loop:

{% endfor %}

And above it add: 

{% endif %}

Find the closing ul:

</ul>

And below it add: 

{% endfor %}

This is how my code looks: 

If you want to use a variant option other than color, you can change the value on line 85 in the above screenshot. 

Next we will add some code to the theme.js assets file.

Find the line that looks like this:

_onSelectChange: function() {

Before the closing } bracket, add: 

var thumbs = document.getElementsByClassName("product-single__thumbnails");

for (var i = 0; i < thumbs.length; i++){
var variantTitle = variant.title;
var variantColor = thumbs[i].getAttribute('data-color');

if (variantTitle.includes(variantColor)) {
$('.product-single__thumbnails[data-color="' + variantColor + '"]').removeClass('hide');
} else {
$('.product-single__thumbnails[data-color="' + variantColor + '"]').addClass('hide');
}
}

The code should look like this:

Hopefully the images are now switching for each variant!