Dynamic DIV by selected variant

gina-a
Visitor
3 0 0

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.

 

Replies 2 (2)

gina-a
Visitor
3 0 0

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 %}

Dominik_Fischer
Shopify Partner
3 0 3

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.