Stock level message only showing when choosing variant

Highlighted
New Member
2 0 0

Hello,

I'm trying to show availability per variant on the product page. I want to show "In stock" and "Not in stock", rather than the actual quantity in stock. It works, except it shows the actual number when I first load the product page (even though a variant is chosen by default), and only when I manually choose a variant it shows "In stock"/"Out of stock" correctly.

 

So on load it shows "Availability: 1". When I change variant and then go back to the same variant and it shows correctly: "Availability: In Stock".

 

In product-template I have this script:

<script>
 var inv_qty = {};
 {% for var in product.variants %}
  {%if var.inventory_quantity<1%}
  inv_qty[{{- var.id -}}] = 'Out of stock';
  {%else%}
  inv_qty[{{- var.id -}}] = 'In stock';
  {%endif%}
 {% endfor %}
</script>

Then I use this HTML to display availability:

<p>Availability: <strong class="variant-inventory">{{ current_variant.inv_qty }}</strong></p>

In theme.js.liquid I have added just the bold line here into the if(variant) of function(evt):

    productPage: function(evt) {
      if (variant) {

        $(this.selectors.variantInventory).html(inv_qty[ variant.id ]);}}

And into this.selectors:

      variantInventory: '.variant-inventory',

 

I suspect it is something about this (in theme.js.liquid) triggering when variant is changed but not on page load, but not sure how to fix:

  function Variants(options) {
    this.$container = options.$container;
    this.product = options.product;
    this.singleOptionSelector = options.singleOptionSelector;
    this.originalSelectorId = options.originalSelectorId;
    this.enableHistoryState = options.enableHistoryState;
    this.currentVariant = this._getVariantFromOptions();

    $(this.singleOptionSelector, this.$container).on(
      'change',
      this._onSelectChange.bind(this)
    );
  }

Any help appreciated :)

0 Likes