-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
267 lines (230 loc) · 8.44 KB
/
script.js
File metadata and controls
267 lines (230 loc) · 8.44 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Shopping cart state
let cart = [];
let cartModal = document.getElementById('cart-modal');
let closeBtn = document.getElementsByClassName('close')[0];
let cartIcon = document.getElementById('cart-icon');
let emptyCartBtn = document.getElementById('empty-cart');
// Load cart from localStorage
function loadCart() {
const savedCart = localStorage.getItem('petStoreCart');
if (savedCart) {
cart = JSON.parse(savedCart);
updateCartUI();
}
}
// Save cart to localStorage
function saveCart() {
localStorage.setItem('petStoreCart', JSON.stringify(cart));
}
// Event listeners
cartIcon.onclick = () => cartModal.style.display = 'block';
closeBtn.onclick = () => cartModal.style.display = 'none';
emptyCartBtn.onclick = emptyCart;
window.onclick = (event) => {
if (event.target == cartModal) {
cartModal.style.display = 'none';
}
};
// Initialize products
function initializeProducts() {
console.log('Initializing products...');
const container = document.getElementById('products-container');
const template = document.getElementById('product-template');
console.log('Available products:', products);
products.forEach(product => {
const productElement = template.content.cloneNode(true);
// Set product data
const card = productElement.querySelector('.product-card');
card.dataset.category = product.category;
const img = productElement.querySelector('.product-image');
img.src = product.imageUrl;
img.alt = product.title;
productElement.querySelector('.product-title').textContent = product.title;
productElement.querySelector('.product-description').textContent = product.description;
productElement.querySelector('.product-price').textContent = `$${product.price}`;
productElement.querySelector('.product-stock').textContent = `Stock: ${product.stock} units`;
// Set up quantity controls
const quantityInput = productElement.querySelector('.quantity-input');
const minusBtn = productElement.querySelector('.minus');
const plusBtn = productElement.querySelector('.plus');
minusBtn.onclick = () => updateQuantity(quantityInput, -1, product.stock);
plusBtn.onclick = () => updateQuantity(quantityInput, 1, product.stock);
quantityInput.onchange = () => validateQuantity(quantityInput, product.stock);
// Set up add to cart button
const addToCartBtn = productElement.querySelector('.add-to-cart-btn');
console.log('Setting up add to cart button for:', product.title);
addToCartBtn.onclick = () => {
console.log('Add to cart button clicked for:', product.title);
addToCart(product, parseInt(quantityInput.value));
};
container.appendChild(productElement);
});
// Set up category filters
setupCategoryFilters();
}
// Update quantity
function updateQuantity(input, change, maxStock) {
let newValue = parseInt(input.value) + change;
validateQuantity(input, maxStock, newValue);
}
// Validate quantity
function validateQuantity(input, maxStock, value = null) {
let newValue = value !== null ? value : parseInt(input.value);
newValue = Math.max(1, Math.min(newValue, maxStock));
input.value = newValue;
}
// Setup category filters
function setupCategoryFilters() {
const filterBtns = document.querySelectorAll('.filter-btn');
filterBtns.forEach(btn => {
btn.addEventListener('click', () => {
// Update active button
filterBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
// Filter products
const category = btn.dataset.category;
const products = document.querySelectorAll('.product-card');
products.forEach(product => {
if (category === 'all' || product.dataset.category === category) {
product.style.display = 'block';
} else {
product.style.display = 'none';
}
});
});
});
}
// Add item to cart
function addToCart(product, quantity) {
console.log('Adding to cart:', product, quantity);
const existingItem = cart.find(item => item.id === product.id);
if (existingItem) {
// Update quantity if product already in cart
const newQuantity = existingItem.quantity + quantity;
if (newQuantity <= product.stock) {
existingItem.quantity = newQuantity;
showNotification(`Updated ${product.title} quantity to ${newQuantity}`);
} else {
showNotification(`Not enough stock available`, 'error');
return;
}
} else {
// Add new item to cart
cart.push({
id: product.id,
title: product.title,
unit_price: product.price,
quantity: quantity,
imageUrl: product.imageUrl
});
showNotification(`Added ${quantity} ${product.title} to cart`);
}
updateCartUI();
saveCart();
}
// Remove item from cart
function removeFromCart(index) {
const item = cart[index];
cart.splice(index, 1);
showNotification(`Removed ${item.title} from cart`);
updateCartUI();
saveCart();
}
// Empty cart
function emptyCart() {
cart = [];
showNotification('Cart emptied');
updateCartUI();
saveCart();
}
// Handle checkout
function handleCheckout() {
if (cart.length === 0) {
showNotification('Your cart is empty', 'error');
return;
}
const total = cart.reduce((sum, item) => sum + (item.unit_price * item.quantity), 0);
cart = [];
updateCartUI();
saveCart();
showNotification(`Order placed! Total: $${total}`, 'success');
cartModal.style.display = 'none';
}
// Update cart UI
function updateCartUI() {
// Update cart count
const cartCount = document.getElementById('cart-count');
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
cartCount.textContent = totalItems;
// Update cart items
const cartItems = document.getElementById('cart-items');
cartItems.innerHTML = '';
cart.forEach((item, index) => {
const cartItem = document.createElement('div');
cartItem.className = 'cart-item';
cartItem.innerHTML = `
<img src="${item.imageUrl}" alt="${item.title}">
<div class="cart-item-details">
<h3 class="cart-item-title">${item.title}</h3>
<p class="cart-item-price">$${item.unit_price} x ${item.quantity}</p>
<p class="cart-item-subtotal">Subtotal: $${item.unit_price * item.quantity}</p>
</div>
<i class="fas fa-trash remove-item" onclick="removeFromCart(${index})"></i>
`;
cartItems.appendChild(cartItem);
});
// Update total
const total = cart.reduce((sum, item) => sum + (item.unit_price * item.quantity), 0);
document.getElementById('cart-total').textContent = `$${total}`;
}
// Show notification
function showNotification(message, type = 'success') {
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
document.body.appendChild(notification);
// Remove notification after 3 seconds
setTimeout(() => {
notification.remove();
}, 3000);
}
// Initialize the store
document.addEventListener('DOMContentLoaded', () => {
initializeProducts();
loadCart();
// Add checkout button event listener
const checkoutBtn = document.getElementById('checkout-btn');
if (checkoutBtn) {
checkoutBtn.addEventListener('click', handleCheckout);
}
});
// Add CSS for notifications
const style = document.createElement('style');
style.textContent = `
.notification {
position: fixed;
bottom: 20px;
right: 20px;
background-color: #4CAF50;
color: white;
padding: 15px 25px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
z-index: 1000;
animation: slideIn 0.5s ease-out;
}
.notification.error {
background-color: #f44336;
}
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
`;
document.head.appendChild(style);