Add product to cart with custom variantID and quantity via Shopify Buy Button

Sascha
Shopify Partner
2 0 0

Hey everyone,

I stuck on a problem conserning my customized Shopify Buy Button:

My goal is to add a item to cart with custom variantID and custom quantity based on user settings on the website. More or less i've managed it to do it but there's one small thing that is missing:

If I click on the button, the Script add's the desired element with the correct variant and quantity to the cart but the cart doesn't open automaticly as it would do if i use the standart button...

I've added a custom template for the button.. Here is the most important part of the script, wich should be enough:

 

options: {
  "product": {
    "iframe": false,
    "templates": {
      "cButton": '<button id="calc-buy" class="button-green">Jetzt für <span class="name">' + buttonName + '</span> bestellen</button>',
    },
    "contents": {
      "img": false,
      "imgWithCarousel": false,
      "title": false,
      "options": false,
      "price": false,
      "description": false,
      "buttonWithQuantity": false,
      "quantity": false,
      "button": false,
      "cButton": true
    },
    "order": [
      'cButton'
    ],
    "DOMEvents": {
      'click #calc-buy': function () {

        var checkoutID = this.component.cart.model.id;
        var productID = this.id;
        var selectedVariant = this.component.selectedVariant;
        var variants = this.component.model.variants;

        this.component.cart.addVariantToCart(variants[calculatorElm.dataset.variantIndex], parseInt(calculatorElm.dataset.quantity));

      }
    }
  }
}
  • I use this API script: https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js
  • All other ui components are standart uncustomized components.
  • And one interesting thing: if I add 'shopify-buy__btn' as class to the custom Button template, the cart is opening but then my script wich adds the custom variant and quantidy don't work properly animore... 

 

Thanks for helping me out,
Sascha

0 Likes
Kristoffer
Shopify Partner
2 0 0

I use version 2.1.7 and I have the same problem.

It seem the "addVariantToCart" function return a Promise in which the view of the cart is render (after it has already been by the "open" cart function) which reset (don't know exactly why) the "isVisible" property.

So here's a quick solution:

cart.addVariantToCart({ id: '12345' }).then(() => {
  cart.open()
});

 

0 Likes