Project 71, E-commerce and business
Shopping Cart with Coupons
The heart of every online shop. Add items, change quantities, try a coupon and watch the free shipping bar fill up. The cart is still there after a reload.
- Main API
- localStorage
- Money
- Intl.NumberFormat
- Dependencies
- None
- Your browser
- Checking
Shop the demo
Add a few items, open the cart and try the codes SAVE10, FREESHIP or WELCOME20. Reload the page: your cart stays.
How it works
- Cart is one small objectItems are stored as product id and quantity. Prices are always read from the product list, so they cannot be edited in the cart.
- Recalculate everythingSubtotal, discount, shipping, tax and total are worked out again on every change, in that order.
- Save after each changeThe cart object is saved to localStorage, so it survives a reload or coming back tomorrow.
const cart = JSON.parse(localStorage.getItem("cart") || "{}"); // { productId: qty }
function totals() {
const sub = Object.entries(cart).reduce((a, [id, q]) => a + products[id].price * q, 0);
const discount = code === "SAVE10" ? sub * 0.1 : 0;
const shipping = sub >= 500 || code === "FREESHIP" ? 0 : 25;
const tax = (sub - discount) * 0.2;
return { sub, discount, shipping, tax, total: sub - discount + shipping + tax };
}
localStorage.setItem("cart", JSON.stringify(cart));