-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcart.js
More file actions
56 lines (47 loc) · 1.82 KB
/
cart.js
File metadata and controls
56 lines (47 loc) · 1.82 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
document.addEventListener("DOMContentLoaded", function () {
const addToCartButtons = document.querySelectorAll('.add-to-cart-btn');
const cartItemsSection = document.querySelector('.cart-items');
const totalPriceElement = document.querySelector('.total-price');
let cart = [];
// Load cart from local storage
if (localStorage.getItem('cart')) {
cart = JSON.parse(localStorage.getItem('cart'));
renderCart();
}
addToCartButtons.forEach(button => {
button.addEventListener('click', function() {
const productName = this.getAttribute('data-name');
const productPrice = parseFloat(this.getAttribute('data-price'));
// Check if product already in cart
const existingProduct = cart.find(item => item.name === productName);
if (existingProduct) {
existingProduct.quantity += 1;
} else {
cart.push({
name: productName,
price: productPrice,
quantity: 1
});
}
// Save cart to local storage
localStorage.setItem('cart', JSON.stringify(cart));
renderCart();
});
});
function renderCart() {
// Clear cart items
cartItemsSection.innerHTML = '';
let total = 0;
cart.forEach(item => {
total += item.price * item.quantity;
cartItemsSection.innerHTML += `
<div class="cart-item">
<h4>${item.name}</h4>
<p>Price: $${item.price}</p>
<p>Quantity: ${item.quantity}</p>
</div>
`;
});
totalPriceElement.textContent = total.toFixed(2);
}
});