forked from janavipandole/Cara
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
509 lines (415 loc) · 17.3 KB
/
Copy pathapp.js
File metadata and controls
509 lines (415 loc) · 17.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Mobile menu functionality
const bar = document.getElementById("bar");
const nav = document.getElementById("navbar");
const close = document.getElementById("close");
if (bar) {
bar.addEventListener("click", () => {
nav.classList.add("active");
});
}
if (close) {
close.addEventListener("click", () => {
nav.classList.remove("active");
});
}
// Single Product Image Switching
var MainImg = document.getElementById("MainImg");
var smallImg = document.getElementsByClassName("small-img");
document.querySelectorAll(".pro img").forEach((img) => {
img.addEventListener("click", function () {
localStorage.setItem("productImage", this.src);
window.location.href = "singleProduct.html";
});
});
if (MainImg) {
for (let i = 0; i < smallImg.length; i++) {
smallImg[i].onclick = function () {
MainImg.src = smallImg[i].src;
}
}
}
// buttons ripple effect
document.addEventListener("DOMContentLoaded", () => {
const buttons = document.querySelectorAll("button.normal, button.white");
buttons.forEach((button) => {
button.addEventListener("click", function (e) {
const rect = this.getBoundingClientRect();
// Calculate coordinates relative to the button
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// Create the ripple element
const ripple = document.createElement("span");
ripple.classList.add("ripple-effect");
// Set position
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
// Append to the button
this.appendChild(ripple);
// Remove the ripple element after the animation finishes to keep the DOM clean
ripple.addEventListener("animationend", () => {
ripple.remove();
});
});
});
});
/* --- START: CART FUNCTIONALITY --- */
// Update cart count badge
function updateCartCount() {
const cart = JSON.parse(localStorage.getItem('productsInCart')) || [];
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
const desktopCount = document.getElementById('desktopCartCount');
const mobileCount = document.getElementById('mobileCartCount');
if (desktopCount) {
desktopCount.textContent = totalItems;
desktopCount.classList.toggle('hidden', totalItems === 0);
}
if (mobileCount) {
mobileCount.textContent = totalItems;
mobileCount.classList.toggle('hidden', totalItems === 0);
}
}
// Call on page load
document.addEventListener('DOMContentLoaded', updateCartCount);
// NEW: Function to toggle visibility of empty cart message
function handleEmptyCartView() {
const cart = JSON.parse(localStorage.getItem('productsInCart')) || [];
const contentWrapper = document.getElementById('cart-content-wrapper');
const emptyContainer = document.getElementById('empty-cart-container');
if (window.location.pathname.includes('cart.html')) {
if (cart.length === 0) {
if (contentWrapper) contentWrapper.style.display = 'none';
if (emptyContainer) emptyContainer.style.display = 'block';
} else {
if (contentWrapper) contentWrapper.style.display = 'block';
if (emptyContainer) emptyContainer.style.display = 'none';
}
}
}
function addToCart(productName, productPrice, productImage, quantity, size) {
let cart = JSON.parse(localStorage.getItem('productsInCart')) || [];
let item = {
name: productName,
price: parseFloat(productPrice.replace('$', '')),
image: productImage,
quantity: parseInt(quantity),
size: size.replace('Size ', '')
};
let existingItem = cart.find(p => p.name === item.name && p.size === item.size);
if (existingItem) {
existingItem.quantity += item.quantity;
} else {
cart.push(item);
}
localStorage.setItem('productsInCart', JSON.stringify(cart));
showToast(`${item.name} (Size: ${item.size}) added to cart!`);
updateCartCount(); // Update badge
}
function showToast(msg, isError = false) {
const toast = document.getElementById('toast');
if (!toast) return;
const icon = document.getElementById('toast-icon');
icon.textContent = isError ? '⚠️' : '✅';
document.getElementById('toast-msg').textContent = msg;
toast.style.background = isError ? '#dc2626' : '#1e293b';
toast.classList.remove('show');
void toast.offsetWidth;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 3000);
}
window.handleAddToCart = function () {
const nameElement = document.getElementById('product-name');
const priceElement = document.getElementById('product-price');
const sizeSelect = document.getElementById('product-size');
const quantityInput = document.getElementById('product-quantity');
const imageElement = document.getElementById('MainImg');
if (!nameElement || !priceElement || !sizeSelect || !quantityInput || !imageElement) {
console.error("Missing product elements on page.");
return;
}
const name = nameElement.innerText;
const price = priceElement.innerText;
const size = sizeSelect.value;
const quantity = parseInt(quantityInput.value);
const image = imageElement.src;
if (size === 'Select Size' || size === "") {
showToast('Please select a size before adding to cart!', true);
return;
}
if (quantity < 1 || isNaN(quantity)) {
showToast('Please enter a valid quantity.', true);
return;
}
addToCart(name, price, image, quantity, size);
updateCartCount(); // Update badge
}
window.loadCart = function () {
let cart = JSON.parse(localStorage.getItem('productsInCart')) || [];
// First, check if we need to show the empty message
handleEmptyCartView();
const tableBody = document.querySelector('#cart table tbody');
if (!tableBody) return;
tableBody.innerHTML = '';
let total = 0;
cart.forEach((item, index) => {
const itemPrice = item.price;
const subtotal = itemPrice * item.quantity;
total += subtotal;
const newRow = tableBody.insertRow();
newRow.insertCell().innerHTML = `<a href="#" onclick="removeItem(${index}); return false;"><i class="fa-regular fa-circle-xmark"></i></a>`;
newRow.insertCell().innerHTML = `<img src="${item.image}" alt="${item.name}">`;
newRow.insertCell().innerHTML = `${item.name}<br><small>Size: ${item.size}</small>`;
newRow.insertCell().innerHTML = `$${itemPrice.toFixed(2)}`;
newRow.insertCell().innerHTML = `<input id="qty-${index}" type="number" value="${item.quantity}" min="1" onchange="updateQuantity(${index}, this.value)">`;
newRow.insertCell().innerHTML = `$${subtotal.toFixed(2)}`;
});
const subtotalCell = document.querySelector('.subtotal table tr:nth-child(1) td:nth-child(2)');
const totalCell = document.querySelector('.subtotal table tr:nth-child(3) td:nth-child(2) strong');
if (subtotalCell) subtotalCell.innerText = `$ ${total.toFixed(2)}`;
if (totalCell) totalCell.innerText = `$ ${total.toFixed(2)}`;
}
window.removeItem = function (index) {
let cart = JSON.parse(localStorage.getItem('productsInCart')) || [];
cart.splice(index, 1);
localStorage.setItem('productsInCart', JSON.stringify(cart));
loadCart(); // This will re-trigger the check through handleEmptyCartView
updateCartCount(); // Update badge
}
window.updateQuantity = function (index, newQuantity) {
let cart = JSON.parse(localStorage.getItem('productsInCart')) || [];
newQuantity = parseInt(newQuantity);
if (newQuantity < 1 || isNaN(newQuantity)) {
newQuantity = 1;
document.getElementById(`qty-${index}`).value = 1;
}
cart[index].quantity = newQuantity;
localStorage.setItem('productsInCart', JSON.stringify(cart));
loadCart();
updateCartCount(); // Update badge
}
window.addEventListener('load', () => {
const cartElement = document.getElementById('cart');
if (cartElement) {
loadCart();
}
});
/* --- END: CART FUNCTIONALITY --- */
/* --- START: THEME TOGGLE FUNCTIONALITY --- */
(function () {
const themeToggle = document.getElementById('themeToggle');
const themeToggleMobile = document.getElementById('themeToggleMobile');
const themeIcon = document.getElementById('themeIcon');
const themeIconMobile = document.getElementById('themeIconMobile');
const html = document.documentElement;
const currentTheme = localStorage.getItem('theme') || 'light';
html.setAttribute('data-theme', currentTheme);
updateThemeIcon(currentTheme);
function updateThemeIcon(theme) {
console.log('Updating icons to:', theme);
const iconClass = theme === 'dark' ? 'ri-sun-line' : 'ri-moon-line';
if (themeIcon) themeIcon.className = iconClass;
if (themeIconMobile) themeIconMobile.className = iconClass;
// Swap logo based on theme
const siteLogo = document.getElementById('siteLogo');
if (siteLogo) {
siteLogo.src = theme === 'dark' ? 'images/Dlogo.png' : 'images/logo.png';
}
}
function toggleTheme() {
const currentTheme = html.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
html.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeIcon(newTheme);
}
if (themeToggle) themeToggle.addEventListener('click', toggleTheme);
if (themeToggleMobile) themeToggleMobile.addEventListener('click', toggleTheme);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', updateThemeIcon);
}
})();
/* --- END: THEME TOGGLE FUNCTIONALITY --- */
(function () {
const paginationSection = document.getElementById('pagination');
if (!paginationSection) return;
const productsPerPage = 16;
const productSection = document.getElementById('product1');
if (!productSection) return;
const productContainers = Array.from(productSection.querySelectorAll('.pro-container'));
let allProducts = [];
productContainers.forEach(container => {
const products = Array.from(container.querySelectorAll('.pro'));
allProducts = allProducts.concat(products);
});
if (allProducts.length === 0) return;
let currentPage = 1;
const totalPages = Math.ceil(allProducts.length / productsPerPage);
if (productContainers.length > 1) {
productContainers.forEach((container, index) => {
if (index > 0) {
container.style.display = 'none';
}
});
}
function showPage(pageNumber) {
allProducts.forEach(product => {
product.style.display = 'none';
});
const startIndex = (pageNumber - 1) * productsPerPage;
const endIndex = startIndex + productsPerPage;
const productsToShow = allProducts.slice(startIndex, endIndex);
const firstContainer = productContainers[0];
firstContainer.innerHTML = '';
firstContainer.style.display = 'flex';
productsToShow.forEach(product => {
product.style.display = 'block';
firstContainer.appendChild(product);
});
productSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
updatePaginationUI(pageNumber);
currentPage = pageNumber;
}
function updatePaginationUI(activePage) {
paginationSection.innerHTML = '';
const prevArrow = document.createElement('a');
prevArrow.href = '#';
prevArrow.innerHTML = '<i class="fa-solid fa-arrow-left"></i>';
prevArrow.classList.add('pagination-arrow');
if (activePage === 1) {
prevArrow.classList.add('disabled');
}
prevArrow.addEventListener('click', (e) => {
e.preventDefault();
if (activePage > 1) {
showPage(activePage - 1);
}
});
paginationSection.appendChild(prevArrow);
for (let i = 1; i <= totalPages; i++) {
const pageLink = document.createElement('a');
pageLink.href = '#';
pageLink.textContent = i;
if (i === activePage) {
pageLink.classList.add('active');
}
pageLink.addEventListener('click', (e) => {
e.preventDefault();
showPage(i);
});
paginationSection.appendChild(pageLink);
}
const nextArrow = document.createElement('a');
nextArrow.href = '#';
nextArrow.innerHTML = '<i class="fa-solid fa-arrow-right"></i>';
nextArrow.classList.add('pagination-arrow');
if (activePage === totalPages) {
nextArrow.classList.add('disabled');
}
nextArrow.addEventListener('click', (e) => {
e.preventDefault();
if (activePage < totalPages) {
showPage(activePage + 1);
}
});
paginationSection.appendChild(nextArrow);
}
showPage(1);
})();
// Back to Top Button Logic
const backToTopBtn = document.getElementById("backToTop");
const ToptobackBtn = document.getElementById("Toptoback");
window.addEventListener("scroll", () => {
// SHOW DOWN BUTTON WHEN USER IS NEAR TOP
if (window.scrollY <= 300) {
ToptobackBtn.classList.add("show");
backToTopBtn.classList.remove("show");
}
// SHOW TOP BUTTON AFTER 300PX
else {
backToTopBtn.classList.add("show");
ToptobackBtn.classList.remove("show");
}
});
// BACK TO TOP
backToTopBtn.addEventListener("click", () => {
window.scrollTo({
top: 0,
behavior: "smooth"
});
});
// SCROLL TO BOTTOM
ToptobackBtn.addEventListener("click", () => {
window.scrollTo({
top: document.body.scrollHeight,
behavior: "smooth"
});
});
// Style Quiz Functionality
window.openQuiz = function () {
document.getElementById('quiz-modal').style.display = 'flex';
}
window.closeQuiz = function () {
document.getElementById('quiz-modal').style.display = 'none';
}
window.selectStyle = function (style) {
closeQuiz();
const products = document.querySelectorAll('.pro');
products.forEach(product => {
if (product.getAttribute('data-category') === style) {
product.style.display = 'block';
} else {
product.style.display = 'none';
}
});
alert(`Showing ${style} style recommendations!`);
}
/* --- START: BUY NOW FUNCTIONALITY --- */
window.buyNow = function(productName, productPrice, productImage, quantity, size) {
// Add to cart first
addToCart(productName, productPrice, productImage, quantity, size);
// Redirect to checkout
window.location.href = 'checkout.html';
}
/* --- START: SEARCH AND FILTER FUNCTIONALITY --- */
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const categoryFilter = document.getElementById('categoryFilter');
if (searchInput && searchBtn) {
// Search functionality
const performSearch = () => {
const searchTerm = searchInput.value.toLowerCase().trim();
const products = document.querySelectorAll('.pro');
products.forEach(product => {
const productName = product.querySelector('h5')?.textContent.toLowerCase() || '';
const productBrand = product.querySelector('.des span')?.textContent.toLowerCase() || '';
const matchesSearch = productName.includes(searchTerm) || productBrand.includes(searchTerm);
if (searchTerm === '' || matchesSearch) {
product.style.display = 'block';
} else {
product.style.display = 'none';
}
});
};
searchBtn.addEventListener('click', performSearch);
searchInput.addEventListener('keyup', (e) => {
if (e.key === 'Enter') {
performSearch();
}
});
}
if (categoryFilter) {
// Category filter functionality
categoryFilter.addEventListener('change', function() {
const selectedCategory = this.value;
const products = document.querySelectorAll('.pro');
products.forEach(product => {
const productCategory = product.getAttribute('data-category');
if (selectedCategory === 'all' || productCategory === selectedCategory) {
product.style.display = 'block';
} else {
product.style.display = 'none';
}
});
});
}
});