Spaces:
Running
Running
File size: 1,427 Bytes
f243b6f c821e69 f2efb9e c821e69 f243b6f c821e69 f243b6f c821e69 f243b6f c821e69 f243b6f c821e69 f2efb9e c821e69 f2efb9e c821e69 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
function getCartItems() {
const cartItems = localStorage.getItem('cart');
return cartItems ? JSON.parse(cartItems) : [];
}
function updateCartIcon() {
const cartItems = getCartItems();
const cartItemCount = cartItems.reduce((total, item) => total + item.quantity, 0);
const cartIcon = document.querySelector('a[href="/cart.html"]');
if (cartIcon) {
cartIcon.textContent = `Cart (${cartItemCount})`;
}
}
function addToCart(product) {
const cartItems = getCartItems();
const existingProductIndex = cartItems.findIndex(item => item.id === product.id);
if (existingProductIndex > -1) {
// If the product already exists in the cart, increment the quantity
cartItems[existingProductIndex].quantity += 1;
} else {
// Otherwise, add the product to the cart with a quantity of 1
cartItems.push({ ...product, quantity: 1 });
}
localStorage.setItem('cart', JSON.stringify(cartItems));
updateCartIcon();
alert('Product added to cart!');
}
function removeFromCart(productId) {
let cartItems = getCartItems();
cartItems = cartItems.filter(item => item.id !== productId);
localStorage.setItem('cart', JSON.stringify(cartItems));
updateCartIcon();
updateCartPage(); // Function to update cart page after removing item
}
// Call updateCartIcon on page load
updateCartIcon();
|