Skip to main content
shoppy.cart.count()
Returns the total number of items in the cart.

Parameters

None

Returns

number Returns 0 if the cart has not been initialized.

Examples

Display cart count

const count = shoppy.cart.count()
document.querySelector('.cart-badge').textContent = count

Update cart badge reactively

shoppy.cart.subscribe((cart) => {
    const count = cart?.totalQuantity ?? 0
    const badge = document.querySelector('.cart-badge')

    badge.textContent = count
    badge.style.display = count > 0 ? 'block' : 'none'
})

Check if cart has items

if (shoppy.cart.count() > 0) {
    showCheckoutButton()
} else {
    showEmptyCartMessage()
}

Header cart icon

function updateCartIcon() {
    const count = shoppy.cart.count()
    const icon = document.querySelector('.cart-icon')

    icon.setAttribute('data-count', count)
    icon.classList.toggle('has-items', count > 0)
}

// Update on any cart change
shoppy.cart.subscribe(updateCartIcon)
This returns the total quantity of all items, not the number of unique line items. For example, 3 t-shirts + 2 hats = count of 5.