DEV Community

Cover image for online
Jodie Farghly
Jodie Farghly

Posted on

online

`

`

`
let cart = JSON.parse(localStorage.getItem('cart')) || [];
function addToCart(name, price) {
cart.push({ name, price });
localStorage.setItem('cart', JSON.stringify(cart));
updateCart();
}
function updateCart() {
document.getElementById('cart-count').textContent = cart.length;
const cartItems = document.getElementById('cart-items');
const total = cart.reduce((sum, item) => sum + item.price, 0);
cartItems.innerHTML = cart.map(item => `<li>${item.name} - $${item.price.toFixed(2)}</li>`).join('');
document.getElementById('cart-total').textContent = total.toFixed(2);
}
function checkout() {
if (cart.length === 0) {
alert('Your cart is empty!');
} else {
alert(`Proceeding to checkout for $${document.getElementById('cart-total').textContent}. (Demo only!)`);
cart = [];
localStorage.removeItem('cart');
updateCart();
}
}
// Initialize cart on load
updateCart();
`

Top comments (0)