openCart() function for Shopify Buy Button JS does not work

1.4k views Asked by At

I like to set up a Shopify shop via a simple HTML/CSS/JS/PHP website structure, where I include the highly customizable Shopify Buy Button JS library.

I followed the tutorial, and everything is set up correctly, as I can fetch and display all my products, which I have set up via the Shopify dashboard.

The default styles and iFrames of the Shopify UI elements (cart, drawer, buy-button, etc.) do not match the style and UX of my website, therefore I want to customize them via css. I deactivated the iFrames of most elements via the directive "iframe: false", and this works properly.

I also want to create a customized toggle button, that opens the cart (instead of the classic toggle button form Shopify, that is fixed to the middle of the right side of the screen).

The weird thing is, I'm not able to open the cart via ui.openCart(), as mentioned in the docs. I'm able to open the cart via ui.openCart() when I do it with a setTimout (3s), but I'm not able to do so via a jQuery click event. What am I doing wrong?

My code so far:

<script src="//sdks.shopifycdn.com/buy-button/1.0.0/buybutton.js"></script>
<script>
var client = ShopifyBuy.buildClient({
  domain: 'domain.myshopify.com',
  storefrontAccessToken: '2b3xxxxxxxxjh5', // previously apiKey, now deprecated
});

ui = ShopifyBuy.UI.init(client);

ui.createComponent('product', {
  id: 23xxxxxx56,
  node: document.getElementById('my-product'),
  options: {
    "product": {
      "iframe": false
    },
    toggle: {
      "iframe": false
    }
  }
});

// -- this does not work --
$('#shoppingCartDropdownInvoker').click(function(){
  ui.openCart();
});

// -- this does work --
setTimeout(function(){
  ui.openCart();
}, 3000);
</script>

The code for #shoppingCartDropdownInvoker is:

<a id="shoppingCartDropdownInvoker" class="btn btn-xs btn-icon btn-text-secondary" href="javascript:;" role="button">
  <span class="fas fa-shopping-cart btn-icon__inner"></span>
</a>
1

There are 1 answers

1
Michael Theodore On

You need to stop the event from bubbling up the chain. Add event.stopPropagation as shown

$('#shoppingCartDropdownInvoker').click(function(event){
  event.stopPropagation();
  ui.openCart();
});