Shopify - Filter variant images

product-template.liquid

{% for media in product.media %}
<li data-thumbnail-color="{{media.alt}}" class="product-single__thumbnails-item product-single__thumbnails-item--{{ section.settings.media_size }} js">

 

theme.js

 

function Variants(options) {
this.$container = options.$container;
this.product = options.product;
this.singleOptionSelector = options.singleOptionSelector;
this.originalSelectorId = options.originalSelectorId;
this.enableHistoryState = options.enableHistoryState;
this.currentVariant = this._getVariantFromOptions();

this._filterThumbnails(this.currentVariant);

$(this.singleOptionSelector, this.$container).on(
'change',
this._onSelectChange.bind(this)
);
}

 

_onSelectChange: function() {
var variant = this._getVariantFromOptions();

this.$container.trigger({
type: 'variantChange',
variant: variant
});

if (!variant) {
return;
}

this._updateMasterSelect(variant);
this._updateImages(variant);
this._filterThumbnails(variant);
this._updatePrice(variant);
this._updateSKU(variant);
this.currentVariant = variant;



if (this.enableHistoryState) {
this._updateHistoryState(variant);
}
},

 

//add new function:

_filterThumbnails: function(variant) {

if( variant.featured_image != null && variant.featured_image.alt != null )
{
$('[data-thumbnail-color]').hide();
var thumbnail_selector = '[data-thumbnail-color="'+variant.option1+'"]';
$(thumbnail_selector).show();
}
else
{
$('[data-thumbnail-color]').show();
}

},

 

Another function:

_filterThumbnails: function(variant) {
// If variant exists on product.
if(variant.option1 != "Default Title"){
$('li[class*="product-single"]:not([data-thumbnail-color="'+variant.option1+'"])').hide();
$('li[class*="product-single"][data-thumbnail-color="'+variant.option1+'"]').show();
var firstVariantPictureValue = $('li[class*="product-single"][data-thumbnail-color="'+variant.option1+'"]').find("a")[0].dataset.zoom ;
var pictureZoom = $('div[class*="product-single__media-wrapper js"]');
for( var i = 0 ; i < pictureZoom.length ;i++){
if(pictureZoom.find('div[id*="ImageZoom-product"]')[i].dataset.zoom == firstVariantPictureValue){
if(pictureZoom[i].classList.contains("hide")){
pictureZoom[i].classList.remove("hide");
console.log("TRUE");
}
}
else{
if(!pictureZoom[i].classList.contains("hide")){
pictureZoom[i].classList.add("hide");
console.log("FALSE");
}
}
}
}
},

Leave a comment