// Example product list with computer, phone, keyboard, mouse, and battery const products = [ { id: 1, name: "Old Computer", price: 100.00, image: "https://via.placeholder.com/200x150?text=Computer" }, { id: 2, name: "Used Smartphone", price: 150.00, image: "https://via.placeholder.com/200x150?text=Phone" }, { id: 3, name: "Wireless Keyboard", price: 30.00, image: "https://via.placeholder.com/200x150?text=Keyboard" }, { id: 4, name: "Wired Mouse", price: 20.00, image: "https://via.placeholder.com/200x150?text=Mouse" }, { id: 5, name: "Rechargeable Battery", price: 10.00, image: "https://via.placeholder.com/200x150?text=Battery" } ]; // Initialize cart (using localStorage to persist data across page reloads) let cart = JSON.parse(localStorage.getItem('cart')) || []; // Function to render product list function renderProductList() { const productListContainer = document.getElementById('product-list'); productListContainer.innerHTML = ''; products.forEach(product => { const productCard = document.createElement('div'); productCard.classList.add('product-card'); productCard.innerHTML = ` ${product.name}

${product.name}

Price: $${product.price.toFixed(2)}

`; productListContainer.appendChild(productCard); }); } // Function to add item to cart function addToCart(productId) { const product = products.find(p => p.id === productId); // Check if the product is already in the cart const cartItem = cart.find(item => item.product.id === productId); if (cartItem) { cartItem.quantity += 1; // Increase quantity if already in cart } else { cart.push({ product, quantity: 1 }); } // Save the cart in localStorage localStorage.setItem('cart', JSON.stringify(cart)); renderCart(); } // Function to render the cart function renderCart() { const cartItemsContainer = document.getElementById('cart-items'); const totalCostContainer = document.getElementById('total-cost'); cartItemsContainer.innerHTML = ''; let totalCost = 0; cart.forEach(item => { const cartItem = document.createElement('li'); const itemTotal = item.product.price * item.quantity; totalCost += itemTotal; cartItem.innerHTML = ` ${item.product.name} (x${item.quantity}) - $${itemTotal.toFixed(2)} `; cartItemsContainer.appendChild(cartItem); }); totalCostContainer.textContent = totalCost.toFixed(2); } // Initialize the page renderProductList(); renderCart();