Custom tag

ajax-cart-product-form

A custom tag which performs a Shopify Cart API /cart/add.js Ajax request once a user submits a product form.

How it works

Once loaded, an <ajax-cart-product-form> element searches for a valid Shopify product form inside itself and subscribes to the form submit event. Once the event is fired, the <ajax-cart-product-form> element collects the form data and sends it as a Shopify Cart API /cart/add.js Ajax request in order to add the product to the cart.

The <ajax-cart-product-form> element must contain only one Shopify product form inside:

sections/main-product.liquid
<ajax-cart-product-form>
  {% form 'product', product %}
    <!-- form content -->
  
    <button type="submit" name="add">
      Add to cart
    </button>
  {% endform %}
</ajax-cart-product-form>

Loading state

When the <ajax-cart-product-form> element initiates an Ajax request, it adds the processing attribute to itself and freezes the “Add to cart” button. Use the attribute to signify that the product form is currently in the process of adding a product to the cart.

assets/style.css
/* Show a loading indicator */
ajax-cart-product-form[processing]:before {
  content: 'Loading';
  display: block;
}

/* Make the "Add to cart" button look visually disabled while loading */
ajax-cart-product-form[processing] [type="submit"] {
  opacity: .7;
  cursor: not-allowed;
  pointer-events: none;
}