Soft Add to Cart Functionality

Step 1: Create addToCart.js File

Create a file names addToCart.js in assets/js/theme/global folder.

Paste this code block in to file.

import $ from 'jquery';
import utils from '@bigcommerce/stencil-utils';
import Swal from './sweet-alert';
import { defaultModal } from './modal';
// eslint-disable-next-line func-names
export default function () {
    const cartProcess = {
        const: {
            modal: defaultModal(),
            $body: $('body'),
            $addToCartButton: '.btnATC',
            quantity: '1',
            cartArgs: {
                action: null, fastcart: null, product_id: null, qty: null,
            },
        },
        func: {
            getCart: (qty, cartItemHash) => {
                const options = {
                    template: 'cart/preview',
                    params: {
                        suggest: cartItemHash,
                    },
                };

                utils.api.cart.getContent(options, (err, response) => {
                    if (err) {
                        return;
                    }

                    cartProcess.const.modal.updateContent(response);
                    // eslint-disable-next-line no-shadow
                    const $cartQuantity = $('[data-cart-quantity]', cartProcess.const.modal.$content);
                    const $cartCounter = $('.navUser-action .cart-count');
                    const cartQuantity = $cartQuantity.data('cart-quantity') || 0;

                    $cartCounter.addClass('cart-count--positive');
                    cartProcess.const.$body.trigger('cart-quantity-update', cartQuantity);
                });
            },
            addToCart: (data, addToCartButton, ATCButtonText) => {
                const formData = new FormData();

                // eslint-disable-next-line guard-for-in,no-restricted-syntax
                for (const key in data) {
                    formData.append(key, data[key]);
                }

                cartProcess.const.modal.open({ size: 'large' });

                utils.api.cart.itemAdd(formData, (err, response) => {
                    const errorMessage = err || response.data.error;

                    if (errorMessage) {
                        const tmp = document.createElement('DIV');
                        tmp.innerHTML = errorMessage;
                        cartProcess.const.modal.close();
                        return Swal.fire({
                            text: tmp.textContent || tmp.innerText,
                            icon: 'error',
                        });
                    }

                    addToCartButton.html(ATCButtonText);

                    // eslint-disable-next-line max-len
                    cartProcess.func.getCart(cartProcess.const.quantity, response.data.cart_item.hash);

                    return true;
                });
            },
        },
    };

    cartProcess.const.$body.on('click', cartProcess.const.$addToCartButton, (event) => {
        const $target = $(event.currentTarget);

        const ATCButtonText = $target.html();

        $(event.currentTarget).text('Adding to cart...');

        event.preventDefault();

        const productIdValue = $(event.currentTarget).data('productId');

        cartProcess.const.cartArgs.action = 'add';
        cartProcess.const.cartArgs.fastcart = '1';
        cartProcess.const.cartArgs.product_id = productIdValue;
        cartProcess.const.cartArgs.qty = cartProcess.const.quantity;

        cartProcess.const.modal.open();

        cartProcess.func.addToCart(cartProcess.const.cartArgs, $target, ATCButtonText);
    });
}

Step 2: Call addToCart function

Open global.js file from asset/js/theme/global.js and place addToCart.js on the import section.

import addToCart from '../global/addToCart';

Then place addToCart(); function call on global.js's onReady() {} function.

Step3: Change 'Add to Cart' Button Attributes

Find card.html file from `templates/components/products' folder.

You should add btnATC class to add to cart button and data-product-id attribute to the add to cart button.

Here is an example:

{{#or customer (if theme_settings.restrict_to_login '!==' true)}}
    {{#if show_cart_action}}
        {{#if add_to_cart_url }}
            <a  data-event-type="product-click" data-product-id="{{id}}" class="button button--small card-figcaption-button theme-btn-primary btnATC">
                <span class="icon-add-to-cart show theme-icon" data-icon="&#xe900;"></span><span class="show">{{lang 'products.add_to_cart'}}</span>
            </a>
        {{/if}}
    {{/if}}
{{/or}}