Update Cart Quantity in Real Time With Cart.JS

In Theme.liquid

This technique was first used on the https://bon-jovi.myshopify.com store.

Include the Cart.js Libraries. This can be done 2 ways. The first way is to include the CDN. The second way is download the files, upload to assets and link The important thing to remember is the include needs to go after the JQuery include. Here is a link to detailed instructions: https://cartjs.org/pages/guide

  <!-- Only include one of the below in your theme. -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.0/cart.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.0/rivets-cart.min.js"></script>
At the bottom of theme.liquid right before the </body> closing tag add the following code to initialize cart.js
  <!-- Initialise Cart.js once the page has loaded -->
  <script type="text/javascript">
      jQuery(function() {
          CartJS.init({{ cart | json }});
      });
  </script>

Displaying Product Count:

To make the cart count display add the below code. The important thing to remember is the data-cart-render="item_count" does all of the heavy lifting, so any standard HTML tag can be substituted for <strong>.
<strong data-cart-render="item_count"></strong>
For the OLM Theme this means locating the cart count in the navbar and replacing the code with the following:
<a class="cartCount" href="/cart"><i class="fa fa-shopping-cart"></i> Cart<span > ( <strong data-cart-render="item_count"></strong> )</span></a>

Attaching Product Button with Cart Count:

In order for the product cart to update the quantity, data must be binded to the product button.

To do this locate the product-add-to-cart-form.liquid (or the location of the product <form></form>), and add data-cart-submit="data-cart-submit" to the form.

The final code should look like:

<form data-cart-submit="data-cart-submit">
Thats It!

Leave a comment