// Sample product data (you can replace this with your actual product data)
const products = [
{ id: 1, name: 'Product 1', price: 19.99, image: 'https://via.placeholder.com/150' },
{ id: 2, name: 'Product 2', price: 29.99, image: 'https://via.placeholder.com/150' },
{ id: 3, name: 'Product 3', price: 39.99, image: 'https://via.placeholder.com/150' },
// Add more products as needed
];
let cart = [];
// Function to render product list
function renderProducts() {
const productList = document.querySelector('.product-list');
productList.innerHTML = '';
products.forEach(product => {
const productElement = document.createElement('div');
productElement.classList.add('product-item');
productElement.innerHTML = `
${product.name}
$${product.price.toFixed(2)}
`; productList.appendChild(productElement); }); } // Function to add item to cart function addToCart(productId) { const product = products.find(p => p.id === productId); if (product) { cart.push(product); updateCartCount(); } } // Function to update cart count function updateCartCount() { const cartCount = document.getElementById('cart-count'); cartCount.textContent = cart.length; } // Function to render cart items function renderCart() { const cartItems = document.getElementById('cart-items'); const cartTotal = document.getElementById('cart-total'); cartItems.innerHTML = ''; let total = 0; cart.forEach(item => { const itemElement = document.createElement('div'); itemElement.innerHTML = `${item.name} - $${item.price.toFixed(2)}
`; cartItems.appendChild(itemElement); total += item.price; }); cartTotal.textContent = total.toFixed(2); } // Event listeners document.addEventListener('DOMContentLoaded', () => { renderProducts(); const cartIcon = document.querySelector('.cart-icon'); const modal = document.getElementById('cart-modal'); const closeModal = document.getElementById('close-modal'); const checkoutBtn = document.getElementById('checkout-btn'); cartIcon.addEventListener('click', () => { renderCart(); modal.style.display = 'block'; }); closeModal.addEventListener('click', () => { modal.style.display = 'none'; }); checkoutBtn.addEventListener('click', () => { alert('Checkout functionality not implemented in this example.'); }); window.addEventListener('click', (event) => { if (event.target === modal) { modal.style.display = 'none'; } }); });
Comments
Post a Comment