document.addEventListener('DOMContentLoaded', () => { updateCartCount(); }); // Function to get cart items from localStorage function getCartItems() { const cart = localStorage.getItem('cart'); return cart ? JSON.parse(cart) : []; } // Function to save cart items to localStorage function saveCartItems(cart) { localStorage.setItem('cart', JSON.stringify(cart)); updateCartCount(); } // Function to update the cart count displayed in the header function updateCartCount() { const cartItems = getCartItems(); const cartCountElement = document.getElementById('cart-count'); if (cartCountElement) { const totalItems = cartItems.reduce((sum, item) => sum + item.quantity, 0); cartCountElement.textContent = totalItems; if (totalItems > 0) { cartCountElement.style.display = 'block'; } else { cartCountElement.style.display = 'none'; } } } // Function to add an item to the cart function addToCart(product) { let cart = getCartItems(); const existingItemIndex = cart.findIndex(item => item.id === product.id); if (existingItemIndex > -1) { cart[existingItemIndex].quantity += 1; } else { cart.push({ ...product, quantity: 1 }); } saveCartItems(cart); alert(`${product.name} added to cart!`); } // Function to remove an item from the cart function removeFromCart(productId) { let cart = getCartItems(); cart = cart.filter(item => item.id !== productId); saveCartItems(cart); // You might want to reload the cart page or update its display after removal if (window.location.pathname.includes('cart.html')) { renderCartItems(); // Re-render cart if on cart page } } // Function to update item quantity in cart function updateQuantity(productId, change) { let cart = getCartItems(); const itemIndex = cart.findIndex(item => item.id === productId); if (itemIndex > -1) { cart[itemIndex].quantity += change; if (cart[itemIndex].quantity <= 0) { cart.splice(itemIndex, 1); // Remove if quantity is 0 or less } saveCartItems(cart); if (window.location.pathname.includes('cart.html')) { renderCartItems(); // Re-render cart if on cart page } } }