Skip to content

Instantly share code, notes, and snippets.

@joe-dempsey
Last active January 31, 2023 16:12
Show Gist options
  • Save joe-dempsey/0c34f1e51e3da90ea4c0d93fa96a28f0 to your computer and use it in GitHub Desktop.
Save joe-dempsey/0c34f1e51e3da90ea4c0d93fa96a28f0 to your computer and use it in GitHub Desktop.
Shopify colors for a product.
{% capture option_titles %}Color,color,Colour,colour{% endcapture %}
<div class="color_swatches_collection">
{% assign option_titles = option_titles | split:',' %}
{% for option in product.options %}
{% if option_titles contains option %}
{% capture option_index %}option{{ forloop.index }}{% endcapture %}
{% assign option_values = product.variants | map: option_index | uniq %}
{% if option_values.size != 0 %}
{% for opt in option_values %}
<div style="background-color:{{ opt | downcase }};" class="option_circles"></div>
{% endfor %}
{% endif %}
{% endif %}
{% endfor %}
</div>
// first is non interactive
// second option where we can grab some variant stuff
{% assign has_color = false %}
{% assign index_color = 0 %}
{% for option in product.options %}
{% capture downcased_option %}{{ option | downcase }}{% endcapture %}
{% if downcased_option contains 'color' %}
{% assign has_color = true %}
{% assign index_color = forloop.index0 %}
{% endif %}
{% endfor %}
{% if has_color %}
<p>Interactive Colors:
{% assign colors = '' %}
{% for variant in product.variants %}
{% capture color %}{{ variant.options[index_color] }}{% endcapture %}
{% capture wrapped_color %}<div
style="background-color:{{ color }};"
class="option_circles"
></div>{% endcapture %}
{% unless colors contains wrapped_color %}
<div
style="background-color:{{ color }};"
class="option_circles"
data-variant-id="{{ variant.id }}"
data-variant-id-image="{{ variant.image.src | img_url }}"
></div>
{% capture colors %}{{ colors }}{{ wrapped_color }}{% endcapture %}
{% endunless %}
{% endfor %}
{% endif %}
<script>
// this controls the variant image selectors on collection template.
$( ".option_circles" ).click(function() {
//console.log("color change!");
var productId = $(this).data('product-id');
var productTargetClass = $(this).data('image-target-class');
var newimageurl = $(this).data('variant-id-image');
if (newimageurl === undefined) {
// no variable image set for the color
} else {
// we have a variable color set for the image
//console.log(productId)
// so set the image
$("." + productTargetClass).attr('src', newimageurl);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment