Hey All,
I’ve been working on a site and couldn’t find a good solution out there for being able to select a product variation by the image you click. So I wrote this. Hope it helps someone.
First off, this goes in the theme.js.liquid file. You should find where your products class is and toss it in there.
Also, you’ll want to go into product.liquid (most likely but will depend on your theme) and find the thumb variations container. From there, you’ll simply add an id ( using image.id ) to each image as they are cycled over.
//get an array of the product variants
var variantsArray = this.variants;
//create an object associating product variant image id's with variant id.
var variantsByImageIdArray = {};
for(var i=0; i<variantsArray.length; i++){
variantsByImageIdArray[(variantsArray[i].featured_image.id)] = variantsArray[i];
}
//create a click event for each image variant in your container (changing the id to your own id)
$('#yourThumbsContainer .product-thumbnail img').click( function(){
// set the variantImage and get it's ID attribute
var variantImage = $(this);
var vId = variantImage.attr('id');
// cycle over each image in the array and find the associated variation based on which image was clicked.
$.each(variantsByImageIdArray, function(i,v){
if(vId == i){
// cycle through the selectors and set each option value based on the variation that was clicked
$.each($('.single-option-selector'), function(i2,v2){
$(this).val(v.options[i2]);
});
// Triggering a change will update the variation selected on the shopify product page.
$('.Single-option-selector').trigger('change');
}
});
});