Ad

Shopify Buy Button Minimum Quantity

- 1 answer

I'm currently using the Shopify Buy Button.

For the most part, I just copy and pasted the embed code and didn't change much.

I have a few products that require a that they buy a quantity of 5 or more of said item.

The typical add to bag button adds only one and inside the shopping cart, when pressed, adds/subtracts one.


My Question(s)

  • Is there a way to set a default quantity when clicking on ADD TO CART?
  • And is there a way to add a default subtract/minus on said item

NOTE: I don't want this for all items, only the specific item that the embed buy code is for.


I've searched the default compenents and the developer section and found the following:

var events = {
  addVariantToCart: function (product) {},
  updateQuantity: function (product) {},
 ...
}

I assume this might be what I am looking for but I can't find any solidified details on how to update said product.

If anyone could help or guide me in the right direction it would be greatly appreciated.


My Embed Code

<div id='product-component-ITEM-ID'></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: 'DOMAIN.myshopify.com',apiKey: 'API-KEY',appId: '6'});
    ShopifyBuy.UI.onReady(client).then(function(ui){ui.createComponent('product',{id:["ITEM-ID"],node:document.getElementById('product-component-{{page.item_id}}'),moneyFormat:'%24%7B%7Bamount%7D%7D',

    options:{
      "product":{
        "variantId":"all",
        "width":"240px",
        "contents":{
          "img":false,
          "imgWithCarousel":false,
          "title":false,
          "variantTitle":false,
          "price":false,
          "description":false,
          "buttonWithQuantity":false,
          "quantity":false
        },
        "text":{
          "button":"ADD TO BAG"
        },
        "styles":{
          "product":{
            "text-align":"left",
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0",
              "margin-bottom":"50px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "title":{
            "font-size":"26px"
          },
          "price":{
            "font-size":"18px"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          },
          "compareAt":{
            "font-size":"15px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "cart":{
        "contents":{
          "button":true
        },
        "styles":{
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "footer":{
            "background-color":"#ffffff"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "modalProduct":{
        "contents":{
          "img":false,
          "imgWithCarousel":true,
          "variantTitle":false,
          "buttonWithQuantity":true,
          "button":false,
          "quantity":false
        },
        "styles":{
          "product":{
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0px",
              "margin-bottom":"0px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "toggle":{
        "iframe":false,
        "sticky":false,
        "templates":{
          "icon":'<i class="fa fa-shopping-bag fa-lg darkgrey" aria-hidden="true"></i>'
        },
        "contents":{
          "icon":true,
          "title":false
        },
        "events":{
          afterInit:function (component)      {
            document.getElementById('cart-toggle').appendChild(component.node);
          },

        },
        "order":[
          'count',
          'icon'
        ],
        "styles":{
          "toggle":{
            "font-family":"Lato,sans-serif",
            "background-color":"#393a39",
            ":hover":{
              "background-color":"#333433"
            },
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "count":{
            "font-size":"13px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "productSet":{
        "styles":{
          "products":{
            "@media(min-width:601px)":{
              "margin-left":"-20px"
            }
          }
        }
      }
    }
    }

    );});}})();
/*]]>*/
</script>
Ad

Answer

After a few hours of experimentation, this is the solution I came up with. My testing so far has shown it to be robust and reliable, but if you find any issues please let me know and I'll see what I can do.

The following is the code, using the example code from the Shopify Buy Button homepage. Unfortunately this won't run in a snippet, but if you put that in an HTML file and run it you can test it.


Full Example Code

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id='product-component-05cfb487fb6' data-minqty='5'></div>

Javascript:

function ShopifyBuyInit() {
    var client = ShopifyBuy.buildClient({
        domain: 'embeds.myshopify.com',
        apiKey: '952162710f94aa7b7644b14b2a94f4a3',
        appId: '6',
    });

    ShopifyBuy.UI.onReady(client).then(function(ui) {
        ui.createComponent('product', {
            id: [3030475907],
            node: document.getElementById('product-component-05cfb487fb6'),
            moneyFormat: '%24%7B%7Bamount%7D%7D',
            options: {
                "product": {
                    "styles": {
                        "button": {
                            "background-color": "#292929",
                            ":hover": {
                                "background-color": "#464646"
                            },
                            ":focus": {
                                "background-color": "#464646"
                            }
                        },
                    },
                    "events": {
                        "addVariantToCart": function(product) {
                            product.model.selectedQuantity = 1;
                            var minQty = $(product.node).data('minqty');
                            if (product.cart.model.lineItemCount < minQty) {
                                product.updateQuantity(function() {
                                    return minQty - (product.cart.model.lineItemCount);
                                });
                            }
                        }
                    }
                },
                "cart": {
                    "events": {
                        "updateItemQuantity": function(cart) {
                            for (let i = 0; i < ui.components.product.length; i++) {
                                var product = ui.components.product[i];
                                var node = product.node;
                                if ($(node).data('minqty')) {
                                    var minQty = $(node).data('minqty');
                                    setTimeout(function() {
                                        setProductQuantity(node, product, minQty, ui);
                                    }, 1);
                                }
                            }
                        }
                    }
                }
            }
        });
    });
}

function setProductQuantity(node, product, minQty, ui) {
    if (product.cart.model.lineItemCount < minQty && product.cart.model.lineItemCount > 0) {
        $('.shopify-buy-cart-wrapper').find('iframe').contents().find("div[id='" + product.cart.model.lineItems[0].id + "']").find('.shopify-buy__quantity-decrement').click();
    }
}

(function() {
    var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
    window.ShopifyBuy && window.ShopifyBuy.UI ? ShopifyBuyInit() : 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;
    }
})();

In-depth Explanation

This works by listening to two events from the Shopify Buy Button: addVariantToCart and updateItemQuantity. The first thing you have to do is add a data-minqty attribute to the product div. We'll use that data attribute later.

<div id='product-component-05cfb487fb6' data-minqty='5'></div>

The first event fires when clicking Add to Cart. We'll listen to it so we can make it add minQty items to the cart (in our example, this is 5).

"addVariantToCart": function(product) {
    product.model.selectedQuantity = 1;
    var minQty = $(product.node).data('minqty');
    if (product.cart.model.lineItemCount < minQty) {
        product.updateQuantity(function() {
            return minQty - product.cart.model.lineItemCount;
        });
    }
}

What that does is first set the selected quantity of the item to 1. This is because the selected quantity is automatically set to the last-added quantity, and if we're adding the item to the cart for the first time it will == minQty (i.e. 5). Then we find the minimum quantity from the data attribute we added earlier (product.node is the product's div element). We check if the quantity is less than minQty, and if it is, we run updateQuantity on the product. For some reason it's relative, so we run it with the difference between minQty and product.cart.model.lineItemCount, which is the current quantity.

The second event fires when changing the quantity from the cart itself. We listen to it so we can ensure customers can't reduce the quantity below minQty.

"updateItemQuantity": function(cart) {
    for (let i = 0; i < ui.components.product.length; i++) {
        var product = ui.components.product[i];
        var node = product.node;
        if ($(node).data('minqty')) {
            var minQty = $(node).data('minqty');
            setTimeout(function() {
                setProductQuantity(node, product, minQty, ui);
            }, 1);
        }
    }
}

Since we don't know exactly which item in the cart had its quantity changed, we go through them all and just check if they have a minQty, and if they have it, whether or not they're below. Then we use setTimeout because this event is fired before the quantity is updated, so if we change it right here it just gets reset. We call this function:

function setProductQuantity(node, product, minQty, ui) {
    if (product.cart.model.lineItemCount < minQty && product.cart.model.lineItemCount > 0) {
        $('.shopify-buy-cart-wrapper').find('iframe').contents().find("div[id='" + product.cart.model.lineItems[0].id + "']").find('.shopify-buy__quantity-decrement').click();
    }
}

This function checks if the new quantity is less than minQty. If it's not, we do nothing (and let the quantity be updated normally). If it is, we want to remove the item from the cart. There's no "remove" button (it normally relies on lowering the quantity to 0 to be removed from the cart), and since we have a minimum quantity this can't happen, so we need to check for this and manually remove it. We just simulate a click on the "quantity decrement" button. We only need to do this once because each time we do it fires updateItemQuantity so it self-loops until the item is removed.


Integrated with Your Code

I couldn't test your code directly, but I've added my changes to your code so hopefully you'll be able to figure it out. It does require jQuery because I don't know enough native Javascript for doing what I needed to do.

<div id='product-component-ITEM-ID' data-minqty='5'></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: 'DOMAIN.myshopify.com',apiKey: 'API-KEY',appId: '6'});
    ShopifyBuy.UI.onReady(client).then(function(ui){ui.createComponent('product',{id:["ITEM-ID"],node:document.getElementById('product-component-{{page.item_id}}'),moneyFormat:'%24%7B%7Bamount%7D%7D',

    options:{
      "product":{
        "variantId":"all",
        "width":"240px",
        "contents":{
          "img":false,
          "imgWithCarousel":false,
          "title":false,
          "variantTitle":false,
          "price":false,
          "description":false,
          "buttonWithQuantity":false,
          "quantity":false
        },
        "events": {
          "addVariantToCart": function(product) {
            product.model.selectedQuantity = 1;
            var minQty = $(product.node).data('minqty');
            if (product.cart.model.lineItemCount < minQty) {
              product.updateQuantity(function() {
                return minQty - (product.cart.model.lineItemCount);
              });
            }
          }
        }
        "text":{
          "button":"ADD TO BAG"
        },
        "styles":{
          "product":{
            "text-align":"left",
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0",
              "margin-bottom":"50px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "title":{
            "font-size":"26px"
          },
          "price":{
            "font-size":"18px"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          },
          "compareAt":{
            "font-size":"15px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "cart":{
        "contents":{
          "button":true
        },
        "events": {
          "updateItemQuantity": function(cart) {
            for (let i = 0; i < ui.components.product.length; i++) {
              var product = ui.components.product[i];
              var node = product.node;
              if ($(node).data('minqty')) {
                var minQty = $(node).data('minqty');
                setTimeout(function() {
                  setProductQuantity(node, product, minQty, ui);
                }, 1);
              }
            }
          }
        }
        "styles":{
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "footer":{
            "background-color":"#ffffff"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "modalProduct":{
        "contents":{
          "img":false,
          "imgWithCarousel":true,
          "variantTitle":false,
          "buttonWithQuantity":true,
          "button":false,
          "quantity":false
        },
        "styles":{
          "product":{
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0px",
              "margin-bottom":"0px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "toggle":{
        "iframe":false,
        "sticky":false,
        "templates":{
          "icon":'<i class="fa fa-shopping-bag fa-lg darkgrey" aria-hidden="true"></i>'
        },
        "contents":{
          "icon":true,
          "title":false
        },
        "events":{
          afterInit:function (component)      {
            document.getElementById('cart-toggle').appendChild(component.node);
          },

        },
        "order":[
          'count',
          'icon'
        ],
        "styles":{
          "toggle":{
            "font-family":"Lato,sans-serif",
            "background-color":"#393a39",
            ":hover":{
              "background-color":"#333433"
            },
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "count":{
            "font-size":"13px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "productSet":{
        "styles":{
          "products":{
            "@media(min-width:601px)":{
              "margin-left":"-20px"
            }
          }
        }
      }
    }
    }

    );});}})();

    function setProductQuantity(node, product, minQty, ui) {
      if (product.cart.model.lineItemCount < minQty && product.cart.model.lineItemCount > 0) {
        $('.shopify-buy-cart-wrapper').find('iframe').contents().find("div[id='" + product.cart.model.lineItems[0].id + "']").find('.shopify-buy__quantity-decrement').click();
      }
    }
/*]]>*/
</script>
Ad
source: stackoverflow.com
Ad