How to Update the Cart Count in Header When Clicking Add to Cart in EComposer

Author: Anna Nguyen 8 views

This guide shows you how to make the cart badge number in your Shopify store’s header update automatically when a customer clicks the Add to Cart button from the EComposer app.

First, you need to install the Ajax cart extension and choose the Show a message option for the Add to Cart button on your product page. The Ajax cart extension is available on the paid plans only.

Then, add a short custom JS code in the Site Settings of EComposer. This setup ensures the cart count updates instantly without reloading the page and works across different Shopify themes. Please find the theme you are using by the original theme name and get the corresponding code

1. With the Local theme

document.addEventListener('ec-cart-added', function (e) {
	fetch('?section_id=helper-cart').then(res => res.text()).then(text => {
		const sectionInnerHTML = new DOMParser().parseFromString(text, 'text/html');
		const cartFormInnerHTML = sectionInnerHTML.getElementById('AjaxCartForm').innerHTML;
		const cartSubtotalInnerHTML = sectionInnerHTML.getElementById('AjaxCartSubtotal').innerHTML;

		if (document.getElementById('AjaxCartForm')) {
			const cartItems = document.getElementById('AjaxCartForm');
			cartItems.innerHTML = cartFormInnerHTML;
			cartItems.ajaxifyCartItems();
			document.getElementById('AjaxCartSubtotal').innerHTML = cartSubtotalInnerHTML;
		}


		document.querySelectorAll('[data-header-cart-count]').forEach(elm => {
			elm.textContent = sectionInnerHTML.querySelector('[data-cart-count]').textContent;
		});
		document.querySelectorAll('[data-header-cart-total').forEach(elm => {
			elm.textContent = sectionInnerHTML.querySelector('[data-cart-total]').textContent;
		});

		if (document.getElementById('screen-reader-info')) {
			document.getElementById('screen-reader-info').innerText = `${KROWN.settings.locales.cart_announcement}`;
			setTimeout(() => {
				document.getElementById('screen-reader-info').innerText = '';
			}, 1000);
		}

	});
})

Leave a Comment

Enjoy a free 3-day trial. Then get your first month for $1. Try Now.