-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
73 lines (65 loc) · 2.75 KB
/
script.js
File metadata and controls
73 lines (65 loc) · 2.75 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
document.addEventListener('DOMContentLoaded', () => {
const cart = [];
const addToCartButtons = document.querySelectorAll('.add-to-cart');
addToCartButtons.forEach(button => {
button.addEventListener('click', () => {
const productId = button.getAttribute('data-product-id');
addToCart(productId);
});
});
function addToCart(productId) {
// Find product by ID
const product = products.find(p => p.id === parseInt(productId));
if (product) {
cart.push(product);
displayCart();
updateCartCount();
}
}
function displayCart() {
const cartItems = document.getElementById('cart-items');
cartItems.innerHTML = '';
cart.forEach((product, index) => {
const cartItem = document.createElement('div');
cartItem.className = 'bg-white shadow-lg rounded-lg overflow-hidden';
cartItem.innerHTML = `
<img class="w-full h-56 object-cover object-center" src="${product.image}" alt="Product">
<div class="p-4">
<h3 class="text-gray-900 font-bold text-xl">${product.name}</h3>
<p class="mt-2 text-gray-600">${product.description}</p>
<div class="flex justify-between items-center mt-4">
<span class="text-gray-900 font-bold">$${product.price.toFixed(2)}</span>
<button class="remove-from-cart text-red-600 hover:text-red-800" data-cart-index="${index}">Remove</button>
</div>
</div>
`;
cartItems.appendChild(cartItem);
});
const removeFromCartButtons = document.querySelectorAll('.remove-from-cart');
removeFromCartButtons.forEach(button => {
button.addEventListener('click', () => {
const cartIndex = button.getAttribute('data-cart-index');
removeFromCart(cartIndex);
});
});
}
function removeFromCart(cartIndex) {
cart.splice(cartIndex, 1);
displayCart();
updateCartCount();
}
function updateCartCount() {
const cartCountElement = document.getElementById('cart-count');
const itemCount = cart.length;
if (itemCount > 0) {
cartCountElement.textContent = itemCount > 9 ? '9+' : itemCount;
cartCountElement.classList.remove('hidden');
} else {
cartCountElement.classList.add('hidden');
}
}
const products = [
{ id: 1, name: 'Tribe Pack 1', description: 'Description of the Tribe Pack 1', price: 20.00, image: 'https://source.unsplash.com/random/400x400?card-game' },
// Add more products as needed
];
});