carolineschnapp
3/11/2014 - 9:47 PM

Code to paste at the very top or bottom of your product.liquid template to make clicks on product thumbnails update product option drop-down

Code to paste at the very top or bottom of your product.liquid template to make clicks on product thumbnails update product option drop-downs.For the Variant Images app.

{% comment %}
Place this in your product.liquid template, either at the top or bottom.
{% endcomment %}
{% if product.variants.size > 1 %}
<script>
(function($) { 
  var variantImages = {},
    thumbnails,
    variants = {};
  {% for variant in product.variants %}
  variants[{{ variant.id }}] = {};
    {% for option in product.options %}
    variants[{{ variant.id }}]['option{{ forloop.index }}'] = {{ variant.options[forloop.index0] | json }}; 
    {% endfor %}
  {% endfor %}
  $.getJSON("/a/variant-images-1?shop=" + Shopify.shop + "&handle={{ product.handle }}", function(data) {
    $.each(data, function(variantId, image) {
      variantImages[image.filename] = variantImages[image.filename] || {};
      {% for option in product.options %}
      if (typeof variantImages[image.filename]['option{{ forloop.index }}'] === 'undefined')  {
        variantImages[image.filename]['option{{ forloop.index }}'] = variants[variantId]['option{{ forloop.index }}'];
      }
      else {
        var optionValue = variantImages[image.filename]['option{{ forloop.index }}'];
        if (optionValue !== null && optionValue !== variants[variantId]['option{{ forloop.index }}']) {
          variantImages[image.filename]['option{{ forloop.index }}'] = null;
        } 
      }
      {% endfor %}
    }); 
    $(window).load(function() {
      thumbnails = $('img[src*="/products/"]').not(':first');
      if (thumbnails.size()) {
        thumbnails.bind('click', function() {
          var imageParts = $(this).attr('src').split('/');
          var image = imageParts[imageParts.length-1].split('?')[0].replace(/(_thumb|_small|_compact|_medium|_large|_grande)/,'');
          if (typeof variantImages[image] !== 'undefined') {
            {% for option in product.options %}
            if (variantImages[image]['option{{ forloop.index }}'] !== null) {
              $('.single-option-selector:eq({{ forloop.index0 }})').val(variantImages[image]['option{{ forloop.index }}']).trigger('change');
            }
            {% endfor %}
          }
        });
      }
    });   
  });
})(jQuery);
</script> 
{% endif %}