tim-m
11/28/2017 - 1:48 AM

Select product variants by clicking their images

Select product variants by clicking their images

$(document).ready(function() {
  thumbnails = $('.slider_1 img[src*="/products/"]').not(':first');
  if (thumbnails.size()) {
    thumbnails.bind('click touchend', function() {
      var image = $(this).attr('src').split('?')[0].replace(/(_\d+x\d+@\dx\.)|(_[0-9x]+\.)|(_\d+x\.)|(_thumb\.)|(_small\.)|(_compact\.)|(_medium\.)|(_large\.)|(_grande\.)/,'.');
      if (typeof variantImages[image] !== 'undefined') {
          productOptions.forEach(function (value, i) {
           optionValue = variantImages[image]['option-'+i];
           if (optionValue !== null && $('.single-option-selector:eq('+i+') option').filter(function() { return $(this).text() === optionValue }).length) {
             $('.single-option-selector:eq('+i+')').val(optionValue).trigger('change');
           }
        });
      }
    });
  }
});
{% comment %}
Place this in your product.liquid template, at the bottom.
{% endcomment %}
{% if product.variants.size > 1 %}
<script>
  var variantImages = {},
    thumbnails,
    variant,
    variantImage,
    optionValue,
    productOptions = [];
    {% for variant in product.variants %}
       variant = {{ variant | json }};
       if ( typeof variant.featured_image !== 'undefined' && variant.featured_image !== null ) {
         variantImage =  variant.featured_image.src.split('?')[0].replace(/http(s)?:/,'');
         variantImages[variantImage] = variantImages[variantImage] || {};
         {% for option in product.options %}
         
           {% assign option_value = variant.options[forloop.index0] %}
           {% assign option_key = 'option-' | append: forloop.index0 %}
         	
           if (typeof variantImages[variantImage][{{ option_key | json }}] === 'undefined') {
             variantImages[variantImage][{{ option_key | json }}] = {{ option_value | json }};
           }
           else {
             var oldValue = variantImages[variantImage][{{ option_key | json }}];
             if ( oldValue !== null && oldValue !== {{ option_value | json }} )  {
               variantImages[variantImage][{{ option_key | json }}] = null;
             }
           }
         {% endfor %}
       }
       productOptions.push(variant);
    {% endfor %}
</script> 
{% endif %}