Skip to content

Instantly share code, notes, and snippets.

@tjmaxwell
Created November 28, 2017 01:48
Show Gist options
  • Save tjmaxwell/0c30e4308a9a7415df1ea06806f5ca3d to your computer and use it in GitHub Desktop.
Save tjmaxwell/0c30e4308a9a7415df1ea06806f5ca3d to your computer and use it in GitHub Desktop.
Select product variants by clicking their images
{% 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 %}
$(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');
}
});
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment