-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
437 lines (374 loc) · 14.3 KB
/
app.js
File metadata and controls
437 lines (374 loc) · 14.3 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// DummyJSON API endpoints
const API_ENDPOINT = 'https://dummyjson.com/products?limit=0';
const CATEGORIES_ENDPOINT = 'https://dummyjson.com/products/categories';
const CATEGORY_PRODUCTS_ENDPOINT = 'https://dummyjson.com/products/category';
// State management
let allProducts = [];
let allCategories = [];
let cart = [];
let currentFilter = '';
let currentSearch = '';
let currentProduct = null;
// Initialize the app
document.addEventListener('DOMContentLoaded', () => {
loadCategories();
loadProducts();
setupEventListeners();
loadCartFromStorage();
updateCartDisplay();
});
// Setup event listeners
function setupEventListeners() {
document.getElementById('categoryFilter').addEventListener('change', (e) => {
currentFilter = e.target.value;
filterAndDisplayProducts();
});
document.getElementById('searchInput').addEventListener('input', (e) => {
currentSearch = e.target.value.toLowerCase();
filterAndDisplayProducts();
});
document.getElementById('cartBtn').addEventListener('click', toggleCart);
document.getElementById('closeCart').addEventListener('click', closeCart);
document.getElementById('closeModal').addEventListener('click', closeModal);
document.getElementById('clearCartBtn').addEventListener('click', clearCart);
document.getElementById('modalAddToCart').addEventListener('click', addCurrentProductToCart);
document.getElementById('productModal').addEventListener('click', (e) => {
if (e.target.id === 'productModal') {
closeModal();
}
});
}
// Fetch available categories from DummyJSON API
async function loadCategories() {
try {
console.log('🔄 Fetching categories from:', CATEGORIES_ENDPOINT);
const response = await fetch(CATEGORIES_ENDPOINT);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const categoriesData = await response.json();
console.log('✅ Categories fetched:', categoriesData);
if (!categoriesData || categoriesData.length === 0) {
console.warn('⚠️ No categories returned from API');
return;
}
// Extract slug and name from each category object
allCategories = categoriesData.map(cat => ({
slug: cat.slug,
name: cat.name
}));
console.log('✅ All categories processed:', allCategories);
// Populate category filter dropdown
const categoryFilter = document.getElementById('categoryFilter');
console.log('🔍 Category filter element:', categoryFilter);
if (!categoryFilter) {
console.error('❌ Category filter element not found');
return;
}
console.log('🔄 Starting to add category options...');
allCategories.forEach((category, index) => {
console.log(`📝 Processing category ${index + 1}:`, category.name, `(${category.slug})`);
const option = document.createElement('option');
option.value = category.slug;
option.textContent = category.name;
categoryFilter.appendChild(option);
console.log(`✅ Added option: ${category.name} (value: ${category.slug})`);
});
console.log('✅ All category options added successfully!');
console.log('📋 Total categories in dropdown:', categoryFilter.options.length);
} catch (error) {
console.error('❌ Error loading categories:', error);
console.error('Stack:', error.stack);
}
}
// Fetch products from DummyJSON API
async function loadProducts() {
try {
console.log('Fetching products from:', API_ENDPOINT);
const response = await fetch(API_ENDPOINT);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Products fetched:', data.products.length);
allProducts = data.products.map(product => ({
id: product.id,
title: product.title,
price: product.price,
description: product.description,
image: product.thumbnail || (product.images && product.images[0]) || '',
images: product.images || [],
category: product.category || 'Other',
rating: {
rate: product.rating || 4.5,
count: Math.floor(Math.random() * 1000) + 100
}
}));
// Extract unique categories from products if API endpoint failed
if (allCategories.length === 0) {
console.log('Extracting categories from products...');
const uniqueCategories = [...new Set(allProducts.map(p => p.category))].sort();
allCategories = uniqueCategories;
populateCategoryDropdown(uniqueCategories);
console.log('Categories extracted from products:', uniqueCategories);
}
filterAndDisplayProducts();
} catch (error) {
console.error('Error loading products:', error);
displayError('Error loading products. Please try again later.');
}
}
// Populate category dropdown
function populateCategoryDropdown(categories) {
const categoryFilter = document.getElementById('categoryFilter');
if (!categoryFilter) {
console.error('Category filter element not found');
return;
}
// Clear existing options except first one
while (categoryFilter.options.length > 1) {
categoryFilter.remove(1);
}
categories.forEach(category => {
const option = document.createElement('option');
option.value = category;
option.textContent = category.charAt(0).toUpperCase() + category.slice(1).replace(/[-_]/g, ' ');
categoryFilter.appendChild(option);
});
}
// Filter and display products
function filterAndDisplayProducts() {
let filtered = allProducts;
// Apply category filter using API endpoint if category selected
if (currentFilter) {
filtered = filtered.filter(product =>
product.category === currentFilter
);
}
// Apply search filter
if (currentSearch) {
filtered = filtered.filter(product =>
product.title.toLowerCase().includes(currentSearch) ||
product.description.toLowerCase().includes(currentSearch)
);
}
// Display filtered count
const filterInfo = document.querySelector('.filter-info');
if (filterInfo) {
filterInfo.textContent = `Showing ${filtered.length} of ${allProducts.length} products`;
}
displayProducts(filtered);
}
// Display products in grid
function displayProducts(products) {
const grid = document.getElementById('productsGrid');
const loading = document.getElementById('loading');
if (products.length === 0) {
grid.innerHTML = '<div class="empty-message" style="grid-column: 1/-1; text-align: center; padding: 50px; color: #999;">No products found</div>';
loading.style.display = 'none';
return;
}
loading.style.display = 'none';
grid.innerHTML = products.map((product, index) => createProductCard(product, index)).join('');
// Add click listeners to "View Details" buttons
document.querySelectorAll('.product-btn').forEach((btn, index) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
openProductModal(products[index]);
});
});
}
// Create product card HTML
function createProductCard(product, index) {
const rating = product.rating ? `★${product.rating.rate}` : '★★★★★';
return `
<div class="product-card">
<img src="${product.image}" alt="${product.title}" class="product-image">
<p class="product-category">${product.category}</p>
<h3 class="product-title">${product.title}</h3>
<div class="product-rating">${rating}</div>
<p class="product-price">$${product.price.toFixed(2)}</p>
<button class="product-btn" data-product-index="${index}">View Details</button>
</div>
`;
}
// Open product modal
function openProductModal(product) {
currentProduct = product;
document.getElementById('modalTitle').textContent = product.title;
document.getElementById('modalImage').src = product.image;
document.getElementById('modalCategory').textContent = `Category: ${product.category}`;
document.getElementById('modalDescription').textContent = product.description || 'No description available';
document.getElementById('modalPrice').textContent = `$${product.price.toFixed(2)}`;
if (product.rating) {
const stars = '★'.repeat(Math.round(product.rating.rate)) + '☆'.repeat(5 - Math.round(product.rating.rate));
document.getElementById('modalRating').textContent = stars;
document.getElementById('modalCount').textContent = `(${product.rating.count} reviews)`;
}
document.getElementById('modalQuantity').value = 1;
document.getElementById('productModal').classList.add('open');
}
// Close modal
function closeModal() {
document.getElementById('productModal').classList.remove('open');
currentProduct = null;
}
// Add current product to cart
function addCurrentProductToCart() {
if (!currentProduct) return;
const quantity = parseInt(document.getElementById('modalQuantity').value);
addToCart(currentProduct, quantity);
closeModal();
}
// Add product to cart
function addToCart(product, quantity = 1) {
const existingItem = cart.find(item => item.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
cart.push({
id: product.id,
title: product.title,
price: product.price,
image: product.image,
quantity: quantity
});
}
saveCartToStorage();
updateCartDisplay();
// Show notification
showNotification(`${product.title} added to cart!`);
}
// Remove from cart
function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
saveCartToStorage();
updateCartDisplay();
}
// Update item quantity
function updateQuantity(productId, newQuantity) {
if (newQuantity <= 0) {
removeFromCart(productId);
return;
}
const item = cart.find(item => item.id === productId);
if (item) {
item.quantity = newQuantity;
saveCartToStorage();
updateCartDisplay();
}
}
// Clear cart
function clearCart() {
if (confirm('Are you sure you want to clear your cart?')) {
cart = [];
saveCartToStorage();
updateCartDisplay();
showNotification('Cart cleared!');
}
}
// Update cart display
function updateCartDisplay() {
const cartCount = document.querySelector('.cart-count');
const cartItems = document.getElementById('cartItems');
const cartTotal = document.getElementById('cartTotal');
// Update cart count
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
cartCount.textContent = totalItems;
// Update cart items
if (cart.length === 0) {
cartItems.innerHTML = '<div class="empty-cart">Your cart is empty</div>';
cartTotal.textContent = '$0.00';
} else {
cartItems.innerHTML = cart.map(item => `
<div class="cart-item">
<img src="${item.image}" alt="${item.title}" class="cart-item-image">
<div class="cart-item-details">
<div class="cart-item-title">${item.title}</div>
<div class="cart-item-price">$${item.price.toFixed(2)}</div>
<div class="cart-item-quantity">
<button class="qty-btn" onclick="updateQuantity(${item.id}, ${item.quantity - 1})">-</button>
<span class="qty-display">${item.quantity}</span>
<button class="qty-btn" onclick="updateQuantity(${item.id}, ${item.quantity + 1})">+</button>
<button class="remove-item" onclick="removeFromCart(${item.id})">Remove</button>
</div>
</div>
</div>
`).join('');
// Calculate total
const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
cartTotal.textContent = `$${total.toFixed(2)}`;
}
}
// Toggle cart sidebar
function toggleCart() {
const sidebar = document.getElementById('cartSidebar');
sidebar.classList.toggle('open');
}
// Close cart
function closeCart() {
document.getElementById('cartSidebar').classList.remove('open');
}
// Local storage functions
function saveCartToStorage() {
localStorage.setItem('ecommerce_cart', JSON.stringify(cart));
}
function loadCartFromStorage() {
const saved = localStorage.getItem('ecommerce_cart');
if (saved) {
cart = JSON.parse(saved);
}
}
// Display error message
function displayError(message) {
const grid = document.getElementById('productsGrid');
grid.innerHTML = `<div class="empty-message" style="grid-column: 1/-1; text-align: center; padding: 50px; color: #ff6b6b;">${message}</div>`;
document.getElementById('loading').style.display = 'none';
}
// Show notification
function showNotification(message) {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #667eea;
color: white;
padding: 15px 25px;
border-radius: 5px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
z-index: 2000;
animation: slideIn 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Add animations
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
`;
document.head.appendChild(style);