-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
63 lines (51 loc) · 1.7 KB
/
script.js
File metadata and controls
63 lines (51 loc) · 1.7 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
// Initialize cart from local storage or empty array
let cart = JSON.parse(localStorage.getItem('cart')) || [];
// 1. Function to add items to cart
function addToCart(name, price) {
// Check if item already exists
const existingItem = cart.find(item => item.name === name);
if (existingItem) {
existingItem.quantity++;
} else {
cart.push({ name, price: parseFloat(price), quantity: 1 });
}
saveAndRefresh();
}
// 2. Function to update the UI
function updateCartUI() {
const cartList = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
const cartCount = document.getElementById('cart-count');
cartList.innerHTML = ''; // Clear current list
let total = 0;
let count = 0;
cart.forEach(item => {
const li = document.createElement('li');
li.textContent = `${item.name} - ₹${item.price} x ${item.quantity}`;
cartList.appendChild(li);
total += item.price * item.quantity;
count += item.quantity;
});
cartTotal.textContent = total.toFixed(2);
cartCount.textContent = count;
}
// 3. Save to Local Storage and update display
function saveAndRefresh() {
localStorage.setItem('cart', JSON.stringify(cart));
updateCartUI();
}
// 4. Clear cart function
function clearCart() {
cart = [];
saveAndRefresh();
}
// Event Listeners for "Add to Cart" buttons
document.querySelectorAll('.add-cart').forEach(button => {
button.addEventListener('click', () => {
const name = button.getAttribute('data-name');
const price = button.getAttribute('data-price');
addToCart(name, price);
});
});
// Load the cart on page start
updateCartUI();