-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
74 lines (67 loc) · 2.49 KB
/
scripts.js
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
74
document.addEventListener('DOMContentLoaded', () => {
fetch('products.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
const productList = document.getElementById('product-list');
data.forEach(product => {
const productItem = document.createElement('div');
productItem.className = 'product';
productItem.innerHTML = `
<img src="${product.image}" alt="${product.name}">
<h3>${product.name}</h3>
<p>Price: $${product.price.toFixed(2)}</p>
<button onclick="addToCart(${product.id})">Add to Cart</button>
`;
productList.appendChild(productItem);
});
})
.catch(error => console.error('Fetch error:', error));
});
let cart = JSON.parse(localStorage.getItem('cart')) || [];
function addToCart(productId) {
fetch('products.json')
.then(response => response.json())
.then(products => {
const product = products.find(p => p.id === productId);
cart.push(product);
localStorage.setItem('cart', JSON.stringify(cart));
displayCart();
})
.catch(error => console.error('Add to cart fetch error:', error));
}
function removeFromCart(productId) {
cart = cart.filter(product => product.id !== productId);
localStorage.setItem('cart', JSON.stringify(cart));
displayCart();
}
function clearCart() {
cart = [];
localStorage.setItem('cart', JSON.stringify(cart));
displayCart();
}
function displayCart() {
const cartItems = document.getElementById('cart-items');
cartItems.innerHTML = '';
let total = 0;
cart.forEach(product => {
const cartItem = document.createElement('div');
cartItem.className = 'cart-item';
cartItem.innerHTML = `
<div>
<h4>${product.name}</h4>
<p>Price: $${product.price.toFixed(2)}</p>
</div>
<button onclick="removeFromCart(${product.id})">Remove</button>
`;
cartItems.appendChild(cartItem);
total += product.price;
});
document.getElementById('total-price').textContent = total.toFixed(2);
}
document.getElementById('clear-cart').addEventListener('click', clearCart);
displayCart();