-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
312 lines (283 loc) · 12.6 KB
/
Copy pathscript.js
File metadata and controls
312 lines (283 loc) · 12.6 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
document.addEventListener('DOMContentLoaded', () => {
let categories = ["electronics", "apparel", "home", "books"];
const productGrid = document.getElementById('product-grid');
const cartCount = document.getElementById('cart-count');
const cartToggle = document.getElementById('cart-toggle');
const cartSidebar = document.getElementById('cart-sidebar');
const closeCartBtn = document.getElementById('close-cart-btn');
const cartOverlay = document.getElementById('cart-overlay');
const cartItemsContainer = document.getElementById('cart-items');
const cartTotalPrice = document.getElementById('cart-total-price');
const checkoutBtn = document.querySelector('.checkout-btn');
const searchInput = document.getElementById('search-input');
const categoryFilter = document.getElementById('category-filter');
const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
const mainNav = document.querySelector('.main-nav');
const navLinks = document.querySelectorAll('.main-nav .nav-link');
let products = [
{
id: 1,
name: "Wireless Bluetooth Headphones",
category: "electronics",
price: 79.99,
image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSNhzvzKJxLjowcveny5ehUQq-mTXPpIg_8PA&s",
description: "Experience premium sound quality with these comfortable, noise-cancelling headphones."
},
{
id: 2,
name: "Vintage Leather Backpack",
category: "apparel",
price: 120.00,
image: "https://images.jdmagicbox.com/quickquotes/images_main/genuine-leather-vintage-handmade-casual-college-day-pack-cross-body-messenger-backpack-2020049161-ls9bux9p.jpg",
description: "Stylish and durable, perfect for daily commute or weekend adventures."
},
{
id: 3,
name: "Smart Home Security Camera",
category: "electronics",
price: 99.50,
image: "https://www.safewise.com/app/uploads/2024/07/Best-Wireless-Cameras-2024_Featured-Image.png",
description: "Keep your home safe with 1080p video, night vision, and motion detection."
},
{
id: 4,
name: "Ergonomic Office Chair",
category: "home",
price: 249.99,
image: "https://m.media-amazon.com/images/I/81qhB9v7ueL._UF894,1000_QL80_.jpg",
description: "Designed for comfort and support during long working hours."
},
{
id: 5,
name: "Classic Novel Collection",
category: "books",
price: 45.00,
image: "https://beautifulbooks.info/wp-content/uploads/2020/08/BN-Old-Leatherbound-books.jpg",
description: "A timeless collection of literary masterpieces for every reader."
},
{
id: 6,
name: "Stainless Steel Coffee Maker",
category: "home",
price: 65.75,
image: "https://m.media-amazon.com/images/I/81CcncO-6wL.jpg",
description: "Brew your perfect cup of coffee every morning with ease."
},
{
id: 7,
name: "Men's Casual T-Shirt",
category: "apparel",
price: 25.00,
image: "https://rukminim2.flixcart.com/image/704/844/xif0q/t-shirt/y/5/p/s-hg-mt-09-11-12-supersquad-original-imagtzxpkaggdgnj.jpeg?q=90&crop=false",
description: "Soft cotton, modern fit, ideal for everyday wear."
},
{
id: 8,
name: "Portable Power Bank 20000mAh",
category: "electronics",
price: 35.99,
image: "https://mobilla.in/cdn/shop/files/mpower725-black1.webp?v=1752826193",
description: "Charge your devices on the go with this high-capacity power bank."
},
{
id: 9,
name: "Yoga Mat Eco-Friendly",
category: "home",
price: 30.00,
image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSDpTJgrCocxzbT-huwPx6JnvMjDXBPYmxx4g&s",
description: "Non-slip and made from sustainable materials for your daily practice."
},
{
id: 10,
name: "Bestseller Thriller Novel",
category: "books",
price: 18.99,
image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT5ly3kNBksFMw5A6ON8xIk25GXUlEyp0s86Q&s",
description: "A gripping story that will keep you on the edge of your seat."
}
];
let cart = [];
function updateCategoryFilter() {
categoryFilter.innerHTML = '<option value="all">All Categories</option>';
categories.forEach(cat => {
const option = document.createElement('option');
option.value = cat;
option.textContent = cat.charAt(0).toUpperCase() + cat.slice(1);
categoryFilter.appendChild(option);
});
}
updateCategoryFilter();
// --- Product Rendering ---
const renderProducts = (filteredProducts) => {
productGrid.innerHTML = ''; // Clear existing products
if (filteredProducts.length === 0) {
productGrid.innerHTML = '<p style="grid-column: 1 / -1; text-align: center; font-size: 1.2rem; color: var(--text-light);">No products found matching your criteria.</p>';
return;
}
filteredProducts.forEach(product => {
const productCard = document.createElement('article');
productCard.classList.add('product-card');
productCard.innerHTML = `
<img src="${product.image}" alt="${product.name}">
<div class="product-info">
<h3>${product.name}</h3>
<p class="category">${product.category}</p>
<p class="price">$${product.price.toFixed(2)}</p>
<button class="btn btn-primary add-to-cart-btn" data-id="${product.id}">
Add to Cart <i class="fas fa-cart-plus"></i>
</button>
</div>
`;
productGrid.appendChild(productCard);
});
addAddToCartListeners();
};
// --- Cart Functionality ---
const updateCartCount = () => {
cartCount.textContent = cart.length;
checkoutBtn.disabled = cart.length === 0;
};
const calculateCartTotal = () => {
const total = cart.reduce((sum, item) => sum + item.price, 0);
cartTotalPrice.textContent = `$${total.toFixed(2)}`;
};
const renderCartItems = () => {
cartItemsContainer.innerHTML = ''; // Clear existing cart items
if (cart.length === 0) {
cartItemsContainer.innerHTML = '<p class="empty-cart-message">Your cart is empty.</p>';
} else {
cart.forEach(item => {
const cartItemDiv = document.createElement('div');
cartItemDiv.classList.add('cart-item');
cartItemDiv.dataset.id = item.id;
cartItemDiv.innerHTML = `
<img src="${item.image}" alt="${item.name}">
<div class="cart-item-info">
<h4>${item.name}</h4>
<p>Category: ${item.category}</p>
</div>
<span class="cart-item-price">$${item.price.toFixed(2)}</span>
<button class="remove-item-btn" data-id="${item.id}" aria-label="Remove item from cart">
<i class="fas fa-trash-alt"></i>
</button>
`;
cartItemsContainer.appendChild(cartItemDiv);
});
addRemoveFromCartListeners();
}
calculateCartTotal();
};
const addToCart = (productId) => {
const productToAdd = products.find(p => p.id === parseInt(productId));
if (productToAdd) {
// For simplicity, we just add the item. For multiple quantities,
// we'd check if it exists and increment quantity.
cart.push(productToAdd);
updateCartCount();
renderCartItems();
openCart(); // Open cart automatically when item is added
}
};
const removeFromCart = (productId) => {
const index = cart.findIndex(item => item.id === parseInt(productId));
if (index > -1) {
cart.splice(index, 1);
updateCartCount();
renderCartItems();
}
};
const addAddToCartListeners = () => {
document.querySelectorAll('.add-to-cart-btn').forEach(button => {
button.onclick = (e) => addToCart(e.currentTarget.dataset.id);
});
};
const addRemoveFromCartListeners = () => {
document.querySelectorAll('.remove-item-btn').forEach(button => {
button.onclick = (e) => removeFromCart(e.currentTarget.dataset.id);
});
};
const openCart = () => {
cartSidebar.classList.add('open');
cartOverlay.style.display = 'block';
};
const closeCart = () => {
cartSidebar.classList.remove('open');
cartOverlay.style.display = 'none';
};
// --- Event Listeners ---
cartToggle.addEventListener('click', (e) => {
e.preventDefault();
cartSidebar.classList.contains('open') ? closeCart() : openCart();
});
closeCartBtn.addEventListener('click', closeCart);
cartOverlay.addEventListener('click', closeCart);
// --- Filtering and Searching ---
const applyFilters = () => {
const searchTerm = searchInput.value.toLowerCase();
const selectedCategory = categoryFilter.value;
const filtered = products.filter(product => {
const matchesSearch = product.name.toLowerCase().includes(searchTerm) ||
product.description.toLowerCase().includes(searchTerm);
const matchesCategory = selectedCategory === 'all' || product.category === selectedCategory;
return matchesSearch && matchesCategory;
});
renderProducts(filtered);
};
searchInput.addEventListener('input', applyFilters);
categoryFilter.addEventListener('change', applyFilters);
// --- Mobile Menu Toggle ---
mobileMenuToggle.addEventListener('click', () => {
mainNav.classList.toggle('open');
mobileMenuToggle.querySelector('i').classList.toggle('fa-bars');
mobileMenuToggle.querySelector('i').classList.toggle('fa-times');
});
// Close mobile menu when a nav link is clicked
navLinks.forEach(link => {
link.addEventListener('click', () => {
if (mainNav.classList.contains('open')) {
mainNav.classList.remove('open');
mobileMenuToggle.querySelector('i').classList.remove('fa-times');
mobileMenuToggle.querySelector('i').classList.add('fa-bars');
}
});
});
// --- Initial Load ---
renderProducts(products); // Display all products initially
updateCartCount();
renderCartItems(); // Initialize cart display
// Handle Sell Form Submission
const sellForm = document.getElementById('sell-form');
sellForm.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.getElementById('product-name').value.trim();
let category = document.getElementById('product-category').value;
const customCategory = document.getElementById('custom-category').value.trim();
const price = parseFloat(document.getElementById('product-price').value);
const image = document.getElementById('product-image').value.trim();
const description = document.getElementById('product-description').value.trim();
if (!name || (!category && !customCategory) || isNaN(price) || !image || !description) {
alert("Please fill in all fields correctly. Select or add a category.");
return;
}
// If custom category provided, use it and add to categories list
if (customCategory) {
category = customCategory.toLowerCase();
if (!categories.includes(category)) {
categories.push(category);
updateCategoryFilter();
}
}
const newProduct = {
id: products.length + 1,
name,
category,
price,
image,
description
};
products.push(newProduct);
renderProducts(products); // Re-render all products including the new one
sellForm.reset();
alert("Product added successfully!");
});
});