Script that updates images on the cart page to show the correct thumbnail as chosen in the Variant Images app.
{% if cart.item_count > 0 %}
<script>
// Script that updates images on the cart page to show the correct thumbnail as chosen in the Variant Images app.
// This works with any markup.
// This works when using Line Item Properties where several items in the cart form can share the same variant ID.
// Author: Caroline Schnapp.
// Place at the top of your cart.liquid template.
(function($) {
var variantImages = {},
productHandles = [];
{% for item in cart.items %}
productHandles.push('{{ item.product.handle }}');
productHandles = $.unique(productHandles);
if (typeof variantImages[{{ item.id | json }}] === 'undefined') {
variantImages[{{ item.id | json }}] = [];
}
variantImages[{{ item.id | json }}].push({{ forloop.index0 }});
{% endfor %}
jQuery(function($) {
$('form[action="/cart"]').each(function() {
var images = $(this).find('img[src*="/products/"]').hide();
var size = images.first().attr('src').match(/thumb|small|compact|medium|large|grande/)[0] || 'small';
for (var i=0;i<productHandles.length;i++){
$.getJSON("/a/variant-images-1?shop=" + Shopify.shop + "&handle=" + productHandles[i], function(data){
$.each(data, function(variantId, image) {
if (typeof variantImages[variantId] !== 'undefined') {
for (var j=0; j<variantImages[variantId].length;j++) {
var oldURLParts = images.eq(variantImages[variantId][j]).attr('src').split('?');
var suffix = '?' + oldURLParts[1];
var prefix = oldURLParts[0].split('/');
prefix.pop();
prefix = prefix.join('/') + '/';
var filename = image.filename.replace('.', '_' + size + '.');
images.eq(variantImages[variantId][j]).attr('src', prefix + filename + suffix).show();
};
}
});
});
}
});
});
})(jQuery);
</script>
{% endif %}