test-space / script.js
KingNish's picture
Implement product page, cart, and checkout functionality with icons and animations (#28)
c821e69 verified
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();