On a product card in the collections page and featured products section, I have product cards of each product with an image and below the image, I have color swatches of the variants the products have.
When the image is hovered on, it shows the 2nd product image: {{ product.images[1] | img_url: '300x400', scale: 3, crop: 'center' }}
refers to the 2nd image from the product images array.
However, when a color swatch is hovered on, I want the featured image to change to the variant image on mouseover.
The code for the product card image:
{% for product in collection.products %}
<!-- this div contains both product-card snippet and color variant snippet -->
<div class="product-card w-50 mb3" data-product-id="{{ product.id }}">
<!-- product card snippet code -->
<a class="link-to-product" href="{{ product.url | within: collection }}">
{% if product.featured_image %}
<div class="card-image reveal mb3">
<img src="{{ product | img_url: '300x400', scale: 3, crop: 'center' }}" alt="{{ product.title }}">
<img class="hidden" src="{{ product.images[1] | img_url: '300x400', scale: 3, crop: 'center' }}" />
</div>
{% endif %}
<div class="card-info flex flex-column items-center tc">
<h5 class="mb2 f6 f5-ns">{{ product.title }}</h5>
<p class="price mb3">
{% if product.compare_at_price %}
<span class="strike">{{ product.compare_at_price | money_with_currency }}</span>
{% endif %}
{{ product.price | money_with_currency }}
</p>
</div>
</a>
<!-- end of color product card snippet -->
<!-- color variant hover snippet code -->
<div class="option-colors">
<div class="product-option-row flex justify-center flex-column flex-row-ns tc tl-ns mb4">
<div class="option-values">
{% for value in option.values %}
{% assign radio_id = 'option-' | append: option_name | append: '-' | append: value | handleize %}
{%- for variant in product.variants -%}
{%- if variant.title contains value -%}
{%- assign productColorOptionURL = product.url | append: "?variant=" | append: variant.id -%}
{%- assign variantImgSrc = variant.image.src | img_url: '300x400', scale: 3, crop: 'center' -%}
{%- break -%}
{%- endif -%}
{%- endfor -%}
<a href="{{ productColorOptionURL }}" data-variant-img="{{ variantImageSrc }}">
<label for="{{ radio_id }}" class="color-swatch-list">
{% if force_colors == true %}
{% include 'option-color' with color: value %}
{% else %}
{{ value }}
{% endif %}
</label>
</a>
{% endfor %}
</div>
</div>
</div>
<!-- end of color variant hover snippet -->
</div>
<!-- main div ends -->
The jQuery code
let
productCardContainer = '[data-product-id]',
productVariantSwatch = '[data-variant-img]',
productMainImage = '.card-image img';
$(productCardContainer)
.find(productVariantSwatch).mouseover(function() {
$(this).(productMainImage).attr('src', $(this).data("variant-img"));
})