How to pull in variable image based on swatch selection on collection page?

New Member
4 0 0

Hello! We added the ability to select a variation under each product on our collection pages. Our theme has an option for swatches so we also integrated that into our collection page. Everything is working great!


However the last step is to dynamically replace the product image with the selected variant image. 

We have 2 kinds of "options" Color & Size for each product.

We made this script that is working and pulls in the correct product image depending on the color selected. But we cant make it work with all options (size for example) - remembering each product has size/color attribute.

$('.swatch label i').closest('label').each(function () {
    $(this).click(function () {
        let varImgUrl = $(this).data('img');
        let featuredImgUrl = $(this).data('featuredimg');

        if (!varImgUrl.includes('/shopify/assets/no-image-2048-')) {
            $(this).closest('.product-thumb').find('.product-thumb-inner img').removeAttr('srcset').attr('src', varImgUrl);
        } else if (featuredImgUrl.length > 0 && !featuredImgUrl.includes('/shopify/assets/no-image-2048-')) {
            $(this).closest('.product-thumb').find('.product-thumb-inner img').removeAttr('srcset').attr('src', featuredImgUrl);
        } else {
            $(this).closest('.product-thumb').find('.product-thumb-inner img').removeAttr('srcset').attr('src', '//');

For the life of me I can't get it to work with the "size" option variation. 

Here is the product image code from the collection loop..

<div class="product-thumb-inner">
      <div class="product-thumb-img-wrap {{bs_class}}">

        {% if product.images.size == 0 %}
            <!-- If the product has no image, display custom placeholder -->
            <img src="{{ 'no-image.gif' | asset_url }}">
        {% else %}

            <img class="product-thumb-img z_index_1" alt="{{product.title | escape }}" srcset="{{ product.featured_media.preview_image.src | img_url: img_url_width }} 1x, {{ product.featured_media.preview_image.src | img_url: img_url_width, scale: 2 }} 2x, {{ product.featured_media.preview_image.src | img_url: img_url_width, scale: 3 }} 3x"/>

                {%- include 'product-image',
                    img: product.featured_media.preview_image,
                    class_name: 'product-thumb-img',
                    spinner: true
        {% endif %}

If anyone can help i would be very greatful!


Shopify Partner
2472 129 406

You have not provide the relavant reference, either a url to an example product or sample of the markup&liquid for the jquery selector being used $('.swatch label i')

You'll probably want to look at the shopify documentation for the product options object


Problem Solved? ✔️Accept and ? Like the solution so you can help others.
Buy me a coffee ☕ or donate to
Confused? Busy? Buy a custom solution