-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCart.js
More file actions
69 lines (56 loc) · 2 KB
/
Cart.js
File metadata and controls
69 lines (56 loc) · 2 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
// Load and display cart items
document.addEventListener("DOMContentLoaded", loadCart);
function loadCart() {
let cart = JSON.parse(localStorage.getItem("cart")) || [];
let container = document.getElementById("cart-items");
container.innerHTML = "";
if (cart.length === 0) {
container.innerHTML = `<p class="empty">Your cart is empty 🛒</p>`;
document.getElementById("total").textContent = "Total: $0";
return;
}
let total = 0;
cart.forEach((item, index) => {
total += item.price * item.qty;
container.innerHTML += `
<div class="cart-item">
<img src="${item.image}" alt="${item.name}">
<div class="item-info">
<h3>${item.name}</h3>
<p>Unit Price: $${item.price}</p>
<p>Quantity: ${item.qty}</p>
</div>
<div class="item-controls">
<button class="qty-btn" onclick="updateQty(${index}, -1)">-</button>
<button class="qty-btn" onclick="updateQty(${index}, 1)">+</button>
<br><br>
<button onclick="removeItem(${index})"
style="background:#e60000;color:white;">Remove</button>
</div>
</div>
`;
});
document.getElementById("total").textContent = `Total: $${total}`;
}
// Update quantity (+ or -)
function updateQty(index, change) {
let cart = JSON.parse(localStorage.getItem("cart")) || [];
cart[index].qty += change;
if (cart[index].qty <= 0) {
cart.splice(index, 1); // remove item
}
localStorage.setItem("cart", JSON.stringify(cart));
loadCart();
}
// Remove item fully
function removeItem(index) {
let cart = JSON.parse(localStorage.getItem("cart")) || [];
cart.splice(index, 1);
localStorage.setItem("cart", JSON.stringify(cart));
loadCart();
}
// Clear all
function clearCart() {
localStorage.removeItem("cart");
loadCart();
}