Shopify Buy Button - updating which variant is selected by default

evenvisionstaff
New Member
7 0 0

I am working on implementing a Buy Button for one of my clients and am hitting an issue with out of stock variants being selected by default.   My implementation is a bit complex, you can see the code below.  Firstly, I am displaying the variants as buttons instead of in a select box.  Then, I am pulling in the inventory info from JSON, and applying a sold_out class to any variants that are sold out, in the afterInit.  This class leads to their button being greyed out.  

The problem is that the first variant is the one selected by default, but oftentimes the first variant is sold out.  I have an afterRedner function that I want to use for looping through the buttons, finding the first not sold out one, and programmatically selecting it.  The problem I am hitting is that, at this point, "sold_out" does not appear to be applied to the buttons.  I've tried this in different functions, but it is not working anywhere.

We do not want to just hide the out of stock variants, because we have a notice over them telling people to fill out a form so they can be notified when it is in stock.

How can I update the code so that an in stock variant will be selected?

Here is the website I am working on, where you can see that an out of stock variant is selected and the in stock one is not - https://st.evenvision.com/plants/details/seaview-sunset-1#

 

<div id='product-component-1604629781276'></div>
<script type="text/javascript">
/*<![CDATA[*/
(function () {
  var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
  if (window.ShopifyBuy) {
    if (window.ShopifyBuy.UI) {
      ShopifyBuyInit();
    } else {
      loadScript();
    }
  } else {
    loadScript();
  }
  function loadScript() {
    var script = document.createElement('script');
    script.async = true;
    script.src=scriptURL;
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
    script.onload = ShopifyBuyInit;
  }
  function ShopifyBuyInit() {
    var client = ShopifyBuy.buildClient({
      domain: 'singing-tree-gardens-nursery.myshopify.com',
      storefrontAccessToken: '5e60ac0ba199b3bac0b49b0a3065447a',
    });
    ShopifyBuy.UI.onReady(client).then(function (ui) {
      ui.createComponent('product', {
        iframe: "false",
        id: [product_id],
        node: document.getElementById('product-component-1604629781276'),
        moneyFormat: '%24%7B%7Bamount%7D%7D',
        options: {
      "product": {
        iframe: false,
        order: [
          'title',
          'variantTitle',
          'options',
          'price',
          'quantity',
          'button',
        ],
       events: {
            'afterInit': function(component) {

              if(jQuery(".shopify_variant").length) {
                jQuery(".views-field-variants").removeClass("active")
              } else {
                jQuery(".views-field-variants").addClass("active")
              }

              var handle = jQuery(".views-field-handle .field-content").text();

              jQuery.getJSON("https://store.singtree.com/products/" + handle + ".json", function(data) {
             
              var variants = data['product']['variants'];
              for(var i = 0; i < variants.length; i++) {
               
              if(variants[i]["inventory_quantity"] <= 0) {               
                jQuery(".shopify_variant").each(function() {
                  var button = jQuery(this);
                  var button_title = button.find(".shopify_variant_title").text();

                  if(button_title == variants[i]["title"]) {
                   button.addClass("sold_out");
                  } 
                });
               }
              }
             });
            },
            'afterRender': function(component) {
              jQuery(".shopify_variant").each(function() {
                console.log(jQuery(this));
                if(jQuery(this).hasClass("sold_out")) {
                  console.log('test');
                }
              });
            },
          },
          DOMEvents: {
            'click .shopify-buy__option-select': function (evt, target) {
              var data = target.dataset;
              var product = ui.components.product;

              for(var i = 0; i < product.length; i++) {
                if(product[i]["handle"] = "[handle]") {
                  product[i].updateVariant(data.option, data.value);
                }
              }
            },
          },
    "text": {
      "button": "Add to Cart"
    },
    "contents": {
      "button": true,
      "quantity": true,
    }
},
  "cart": {
    "styles": {
      "button": {
        "padding": "17px",
        ":hover": {
          "background-color": "#AD5D72"
        },
        "background-color": "#a44b63",
        ":focus": {
          "background-color": "#AD5D72"
        },
        "border-radius": "0px"
      }
    },
    "text": {
      "total": "Subtotal",
      "button": "Checkout"
    },
  "popup": false
  },
  "toggle": {
    "styles": {
      "toggle": {
        "background-color": "#a44b63",
        ":hover": {
          "background-color": "#AD5D72"
        },
        ":focus": {
          "background-color": "#AD5D72"
        }
      }
    }
  },
  "option" : {
    iframe: false,
    "templates": {
      "option": `<div class={{data.classes.option.option}} id="shopify_button_section" data-element="option.option">
        <div class="{{data.classes.option.wrapper}}" data-element="option.wrapper">
          <div>
            {{#data.values}}
              <div class="shopify_variant {{#selected}} active {{/selected}}"> <div class="shopify_variant_title">{{name}}</div> <input type="submit" {{#data.styleAttr}} {{name}} {{/data.styleAttr}} data-value="{{name}}" data-option={{data.name}} class="shopify-button {{#disabled}}{{data.classes.option.optionDisabled}}{{/disabled}} {{#selected}} .active {{data.classes.option.optionSelected}}{{/selected}} {{data.classes.option.option}}  " value="{{#selected}}Selected{{/selected}} {{^selected}}Select{{/selected}}"></input></div> <br />
            {{/data.values}}
          </div>
        </div>
      </div>`,
    },
  },
},
      });
    });
  }
})();
/*]]>*/
</script>

 

  and am

0 Likes