All things Shopify and commerce
I'm trying to show/hide certain div blocks on product page based on variant selected. What i've tried:
{%- assign current_variant = product.selected_or_first_available_variant -%}
{% if current_variant.sku == "enter-sku-here" %}
<p>do something</p>
{% endif %}
or
{%- assign current_variant = product.selected_or_first_available_variant -%}
{% if current_variant.id == enter-id-here %}
<p>do something</p>
{% endif %}
Unfortunately neither have worked. With the variant.id, I have been able to get the div block to show, but it doesn't change when new variants are selected even though the URL of the product page changes to show the new variant id.
I've also tried using Custom Fields Metadata for variants. Again, this makes the metadata entered show up, but doesn't change when a new variant is selected:
{% for variant in product.variants %}
{% if variant.metafields.namespace.key != blank %}
<div>{{variant.metafields.namespace.key}}</div>
{% endif %}
{% endfor %}
Hey, just stumbled upon the same question. You have to do this with Javascript.
Based on this discussion about passing values from liquid to js: https://community.shopify.com/c/Technical-Q-A/Display-product-variants-metafields/td-p/555439
1. Pass the data from your template to Javascript (add this to your product-template.liquid)
<script>
var isPreOrderValues = {};
{% for variant in product.variants %}
isPreOrderValues["{{variant.id}}"] = {{ variant.metafields.airtable.is_preorder | json | default: 'f'}};
{% endfor %}
</script>
2. To show/hide, add a div with a new selector in product-template.liquid. This one is hidden by default because of class = "hide":
<div id="IsPreOrder" class="hide badge__pre-order">PRE-ORDER</div>
3. Add the div selector to theme.Product.selectors
this.selectors = {
...,
...,
$isPreOrder: $('#IsPreOrder', this.$container),
}
4. Add your logic to the productPage update.
productPage: function(options) {
var self = this;
...
...
var is_preorder = isPreOrderValues[variant.id]
if (variant) {
....
// Update IsPreOrder div
if (is_preorder == 't') {
this.selectors.$isPreOrder.removeClass('hide');
} else {
this.selectors.$isPreOrder.addClass('hide');
}
}
...
}
It could be that the Javascript of your theme is different but it should work like this somehow.
Are you ready to take your business to the next level? Look no further than the latest ...
By SarahF_Shopify Apr 15, 2024We’re keeping the ball rolling to make sure you’re always ahead of the game. So buckle ...
By JasonH Apr 8, 2024Portrait of Stephen positioned next to an image of planet Earth, with the Stephen's World ...
By JasonH Mar 18, 2024