-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
43 lines (37 loc) · 1.11 KB
/
script.js
File metadata and controls
43 lines (37 loc) · 1.11 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
// Cart functionality
let cart = JSON.parse(localStorage.getItem('cart')) || [];
function addToCart(name, price) {
const product = { name, price };
cart.push(product);
localStorage.setItem('cart', JSON.stringify(cart));
alert(`${name} added to cart!`);
}
function renderCart() {
const cartItems = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
if (cartItems && cartTotal) {
cartItems.innerHTML = '';
let total = 0;
cart.forEach((item, index) => {
const itemDiv = document.createElement('div');
itemDiv.innerHTML = `
<p>${item.name} - $${item.price.toFixed(2)}</p>
<button onclick="removeFromCart(${index})">Remove</button>
`;
cartItems.appendChild(itemDiv);
total += item.price;
});
cartTotal.textContent = `Total: $${total.toFixed(2)}`;
}
}
function removeFromCart(index) {
cart.splice(index, 1);
localStorage.setItem('cart', JSON.stringify(cart));
renderCart();
}
function checkout() {
alert('Thank you for your purchase!');
cart = [];
localStorage.removeItem('cart');
renderCart();
}