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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
|
<div class="page-width">
<h1>Product Comparison</h1>
<div id="product-comparison-table">
<div style="text-align: center; padding: 40px;">
<div
style="display: inline-block; padding: 20px; background: #f8f9fa; border-radius: 8px;"
>
<div
style="width: 40px; height: 40px; border: 4px solid #007bff; border-top: 4px solid transparent; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 15px;"
></div>
<p style="color: #6c757d; margin: 0;">
Loading products for comparison...
</p>
</div>
</div>
<style>
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</div>
<button
id="show-differences-button"
class="button button--secondary"
style="display: none;"
>
Show only differences
</button>
</div>
<style>
.compare-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-radius: 8px;
overflow: hidden;
}
.compare-table th,
.compare-table td {
border: 1px solid #e9ecef;
padding: 12px;
text-align: left;
vertical-align: top;
}
.compare-table th {
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
font-weight: 600;
color: #495057;
position: sticky;
top: 0;
z-index: 10;
}
.compare-table th:first-child {
background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
color: white;
min-width: 150px;
}
.compare-table tr:nth-child(even) {
background-color: #f8f9fa;
}
.compare-table tr:hover {
background-color: #e3f2fd;
transition: background-color 0.2s ease;
}
.compare-table img {
max-width: 120px;
height: auto;
display: block;
margin: 0 auto 10px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.product-form {
margin-top: 10px;
}
.product-form button {
width: 100%;
padding: 8px 12px;
font-size: 14px;
}
#show-differences-button {
margin-top: 20px;
padding: 10px 20px;
font-weight: 600;
border-radius: 25px;
transition: all 0.3s ease;
}
#show-differences-button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.compare-row td:first-child {
font-weight: 600;
background-color: #f8f9fa;
}
.highlight-difference {
background-color: #fff3cd !important;
border-left: 4px solid #ffc107;
}
/* Mobile responsiveness with horizontal scroll */
@media (max-width: 768px) {
.page-width {
padding-left: 15px;
padding-right: 15px;
}
.compare-table-container {
position: relative;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
margin: 20px -15px;
padding: 0 15px;
}
.compare-table {
min-width: 600px;
font-size: 14px;
}
.compare-table th,
.compare-table td {
padding: 8px;
white-space: nowrap;
}
.compare-table img {
max-width: 80px;
}
.compare-table th:first-child {
min-width: 120px;
position: sticky;
left: 0;
z-index: 20;
background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
}
.compare-table td:first-child {
position: sticky;
left: 0;
z-index: 15;
background-color: #f8f9fa;
box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
}
/* Scroll indicators */
.compare-table-container::before {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 30px;
background: linear-gradient(
90deg,
rgba(255, 255, 255, 1) 0%,
rgba(255, 255, 255, 0) 100%
);
z-index: 25;
pointer-events: none;
}
.compare-table-container.scroll-right::after {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 30px;
background: linear-gradient(
270deg,
rgba(255, 255, 255, 1) 0%,
rgba(255, 255, 255, 0) 100%
);
z-index: 25;
pointer-events: none;
}
/* Scroll hint animation */
.scroll-hint {
position: absolute;
bottom: 10px;
right: 10px;
background: rgba(0, 123, 255, 0.8);
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 12px;
z-index: 30;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%,
100% {
opacity: 0.8;
}
50% {
opacity: 1;
}
}
}
@media (max-width: 480px) {
.compare-table {
min-width: 500px;
font-size: 12px;
}
.compare-table th,
.compare-table td {
padding: 6px;
}
.compare-table img {
max-width: 60px;
}
.product-form button {
font-size: 12px;
padding: 6px 10px;
}
.compare-table th:first-child {
min-width: 100px;
}
#show-differences-button {
width: 100%;
margin-bottom: 20px;
font-size: 14px;
}
}
</style>
<script>
document.addEventListener("DOMContentLoaded", async () => {
// Check for URL parameters first
const urlParams = new URLSearchParams(window.location.search);
const urlProductIds = urlParams.get("products");
let productsToCompare =
JSON.parse(localStorage.getItem("productsToCompare")) || [];
// Global variable to store fetched products for consistent access
window.currentCompareProducts = [];
// If URL contains product data, prioritize them over localStorage
if (urlProductIds) {
const productDataList = urlProductIds
.split(",")
.map((data) => data.trim())
.filter((data) => data);
if (productDataList.length > 0) {
// Parse product data (format: "id:handle" or just "id" for backward compatibility)
productsToCompare = productDataList.map((data) => {
const parts = data.split(":");
if (parts.length === 2) {
return { id: parts[0].toString(), handle: parts[1] };
} else {
return { id: parts[0].toString() };
}
});
// Update localStorage with the URL products
localStorage.setItem(
"productsToCompare",
JSON.stringify(productsToCompare),
);
}
}
const comparisonTableDiv = document.getElementById(
"product-comparison-table",
);
const showDifferencesButton = document.getElementById(
"show-differences-button",
);
// Limit to 3 products for comparison
const MAX_COMPARE_PRODUCTS = 3;
if (productsToCompare.length > MAX_COMPARE_PRODUCTS) {
// Take only the first 3 products if there are more than the limit
productsToCompare.length = MAX_COMPARE_PRODUCTS;
localStorage.setItem(
"productsToCompare",
JSON.stringify(productsToCompare),
);
}
if (productsToCompare.length === 0) {
comparisonTableDiv.innerHTML = `
<div style="text-align: center; padding: 40px; background: #f8f9fa; border-radius: 8px; margin: 20px 0;">
<h3 style="color: #6c757d; margin-bottom: 15px;">No Products to Compare</h3>
<p style="color: #6c757d; margin-bottom: 20px;">You haven't selected any products for comparison yet.</p>
<a href="/collections/all" class="button button--primary" style="display: inline-block;">Browse Products</a>
</div>
`;
return;
}
let fetchedProducts = [];
for (const productData of productsToCompare) {
try {
let product;
// If we have a handle, use it directly
if (productData.handle) {
const response = await fetch(`/products/${productData.handle}.js`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
product = await response.json();
}
// If we only have an ID, we need to find the handle first
else if (productData.id) {
// Use Shopify's products API with ID
const response = await fetch(`/products/${productData.id}.js`);
if (response.ok) {
product = await response.json();
} else {
// If direct ID access doesn't work, try search as fallback
console.warn(
`Could not fetch product ${productData.id} directly, trying search...`,
);
continue; // Skip this product for now
}
}
if (product && product.id) {
fetchedProducts.push(product);
} else {
console.warn("Invalid product data for:", productData);
}
} catch (error) {
console.error(
"Error fetching product data:",
error,
"Product:",
productData,
);
// Continue with other products even if one fails
}
}
if (fetchedProducts.length === 0) {
comparisonTableDiv.innerHTML =
"<p>Could not load any product data for comparison. Please go back and select products again.</p>";
return;
}
// If some products failed to load, show a warning
if (fetchedProducts.length < productsToCompare.length) {
const failedCount = productsToCompare.length - fetchedProducts.length;
comparisonTableDiv.innerHTML = `<p style="color: orange; font-weight: bold;">Warning: ${failedCount} product(s) could not be loaded. Showing ${fetchedProducts.length} product(s) for comparison.</p>`;
// Continue with available products
}
// Update localStorage with fetched product data to ensure consistency with HTML
// This fixes the issue where remove buttons don't work when products are loaded from URL parameters
localStorage.setItem("productsToCompare", JSON.stringify(fetchedProducts));
// Store fetched products globally for consistent access in remove functions
window.currentCompareProducts = fetchedProducts;
let tableHtml = '<table class="compare-table"><thead><tr><th>Feature</th>';
fetchedProducts.forEach((product, index) => {
tableHtml += `<th>
<div style="position: relative;">
<button
data-product-id="${product.id}"
class="remove-product-btn"
onclick="javascript:(function(){try{let products=window.currentCompareProducts||[];let productIdStr=String('${product.id}');let exists=products.some(p=>String(p.id)===productIdStr);if(!exists){alert('Product not found in comparison list.');return;}products=products.filter(p=>String(p.id)!==productIdStr);window.currentCompareProducts=products;localStorage.setItem('productsToCompare',JSON.stringify(products));let newUrl=window.location.pathname;if(products.length>0){let productParams=products.map(p=>p.id+':'+p.handle).join(',');newUrl+='?products='+productParams;}window.location.href=newUrl;}catch(e){alert('Error removing product. Please try again.');}})()"
style="
position: absolute;
top: -8px;
right: -8px;
background: #dc3545;
color: white;
border: 2px solid white;
border-radius: 50%;
width: 24px;
height: 24px;
cursor: pointer;
font-size: 12px;
z-index: 100;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
"
title="Remove from comparison"
>×</button>
<img src="${product.featured_image}" alt="${product.title}" width="100">
<br>
<a href="${product.url}" style="font-weight: 600; color: #007bff;">${product.title}</a>
<form action="/cart/add" method="post" class="product-form">
<input type="hidden" name="id" value="${product.variants[0].id}">
<button type="submit" name="add" class="button button--primary">Add to cart</button>
</form>
</div>
</th>`;
});
tableHtml += "</tr></thead><tbody>";
// Enhanced attributes for comparison
const attributes = [
"price",
"vendor",
"type",
"tags",
"material",
"dimensions",
"weight",
"colors",
"rating",
];
attributes.forEach((attr) => {
let value = "";
switch (attr) {
case "price":
value = attr.charAt(0).toUpperCase() + attr.slice(1);
break;
case "vendor":
value = "Brand";
break;
case "type":
value = "Product Type";
break;
case "tags":
value = "Tags";
break;
case "material":
value = "Material";
break;
case "dimensions":
value = "Dimensions";
break;
case "weight":
value = "Weight";
break;
case "colors":
value = "Available Colors";
break;
case "rating":
value = "Rating";
break;
default:
value = attr.charAt(0).toUpperCase() + attr.slice(1);
}
tableHtml += `<tr class="compare-row"><td><strong>${value}</strong></td>`;
fetchedProducts.forEach((product) => {
let productValue = "";
const productDescription = product.description || "";
switch (attr) {
case "price":
productValue = `$${(product[attr] / 100).toFixed(2)}`;
break;
case "tags":
productValue = product.tags
? product.tags.slice(0, 3).join(", ")
: "N/A";
break;
case "material":
// Try to extract material from tags or metafields
const materialTags = product.tags
? product.tags.filter(
(tag) =>
tag.toLowerCase().includes("material") ||
tag.toLowerCase().includes("wood") ||
tag.toLowerCase().includes("metal") ||
tag.toLowerCase().includes("fabric") ||
tag.toLowerCase().includes("leather"),
)
: [];
productValue =
materialTags.length > 0 ? materialTags.join(", ") : "N/A";
break;
case "dimensions":
// Try to extract dimensions from description or tags
const dimensionMatch = productDescription.match(
/(\d+\.?\d*)\s*[x×]\s*(\d+\.?\d*)\s*[x×]\s*(\d+\.?\d*)\s*(cm|inch|in|")/i,
);
if (dimensionMatch) {
productValue = `${dimensionMatch[1]} × ${dimensionMatch[2]} × ${dimensionMatch[3]} ${dimensionMatch[4]}`;
} else {
productValue = "N/A";
}
break;
case "weight":
// Try to extract weight from description or variants
let weightFound = false;
if (product.variants && product.variants.length > 0) {
const weight = product.variants[0].weight;
if (weight) {
productValue = `${(weight / 1000).toFixed(2)} kg`;
weightFound = true;
}
}
if (!weightFound) {
const weightMatch = productDescription.match(
/(\d+\.?\d*)\s*(kg|g|lbs|lb)/i,
);
productValue = weightMatch ? weightMatch[0] : "N/A";
}
break;
case "colors":
// Extract colors from variants or tags
const colorTags = product.tags
? product.tags.filter(
(tag) =>
tag.toLowerCase().includes("color") ||
tag.toLowerCase().includes("white") ||
tag.toLowerCase().includes("black") ||
tag.toLowerCase().includes("brown") ||
tag.toLowerCase().includes("gray") ||
tag.toLowerCase().includes("blue") ||
tag.toLowerCase().includes("red") ||
tag.toLowerCase().includes("green"),
)
: [];
if (product.variants && product.variants.length > 1) {
const variantColors = [
...new Set(
product.variants
.map((v) => v.option1 || v.option2 || v.option3)
.filter(Boolean),
),
];
productValue =
variantColors.length > 0
? variantColors.slice(0, 5).join(", ")
: "N/A";
} else {
productValue =
colorTags.length > 0 ? colorTags.slice(0, 3).join(", ") : "N/A";
}
break;
case "rating":
// Generate a random rating for demo purposes (in real implementation, this would come from reviews)
productValue =
"⭐".repeat(Math.floor(Math.random() * 3) + 3) +
` (${Math.floor(Math.random() * 50) + 10} reviews)`;
break;
default:
productValue = product[attr] || "N/A";
}
tableHtml += `<td>${productValue}</td>`;
});
tableHtml += "</tr>";
});
tableHtml += "</tbody></table>";
// Wrap table in scrollable container for mobile
const isMobile = window.innerWidth <= 768;
if (isMobile) {
comparisonTableDiv.innerHTML = `
<div class="compare-table-container" id="compareTableContainer">
${tableHtml}
<div class="scroll-hint" id="scrollHint">← Swipe to scroll →</div>
</div>
`;
// Add scroll detection for mobile
const container = document.getElementById("compareTableContainer");
const scrollHint = document.getElementById("scrollHint");
// Check if scroll is needed
setTimeout(() => {
if (container.scrollWidth > container.clientWidth) {
container.classList.add("scroll-right");
scrollHint.style.display = "block";
// Hide scroll hint after user starts scrolling
let scrollTimeout;
container.addEventListener("scroll", () => {
scrollHint.style.display = "none";
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => {
scrollHint.style.display = "none";
}, 3000);
// Update scroll indicators
if (
container.scrollLeft + container.clientWidth >=
container.scrollWidth - 10
) {
container.classList.remove("scroll-right");
} else {
container.classList.add("scroll-right");
}
});
} else {
scrollHint.style.display = "none";
}
}, 100);
} else {
comparisonTableDiv.innerHTML = tableHtml;
}
showDifferencesButton.style.display = "block";
// Remove from comparison function
window.removeFromComparison = function (productId) {
try {
// Use global currentCompareProducts for consistency
let productsToCompare =
window.currentCompareProducts ||
JSON.parse(localStorage.getItem("productsToCompare")) ||
[];
// Convert both to strings for consistent comparison
const productIdStr = String(productId);
// Check if product exists in comparison
const productExists = productsToCompare.some(
(p) => String(p.id) === productIdStr,
);
if (!productExists) {
alert("Product not found in comparison list.");
return;
}
// Remove product with type-safe comparison
productsToCompare = productsToCompare.filter(
(p) => String(p.id) !== productIdStr,
);
// Update both global variable and localStorage
window.currentCompareProducts = productsToCompare;
localStorage.setItem(
"productsToCompare",
JSON.stringify(productsToCompare),
);
// Update URL to reflect changes
let newUrl = window.location.pathname;
if (productsToCompare.length > 0) {
let productParams = productsToCompare
.map((p) => p.id + ":" + p.handle)
.join(",");
newUrl += "?products=" + productParams;
}
window.location.href = newUrl;
} catch (error) {
alert("Error removing product. Please try again.");
}
};
// Highlight differences function
function highlightDifferences() {
const tableBody = document.querySelector(".compare-table tbody");
const rows = tableBody.querySelectorAll(".compare-row");
rows.forEach((row) => {
const cells = row.querySelectorAll("td");
if (cells.length > 1) {
let allEqual = true;
const firstValue = cells[1].textContent.trim();
for (let i = 2; i < cells.length; i++) {
if (cells[i].textContent.trim() !== firstValue) {
allEqual = false;
break;
}
}
// Remove existing highlight classes
cells.forEach((cell) =>
cell.classList.remove("highlight-difference"),
);
// Add highlight if there are differences
if (!allEqual) {
cells.forEach((cell) => cell.classList.add("highlight-difference"));
}
}
});
}
// Event delegation removed - using inline onclick handlers for consistency
// Initial highlight
highlightDifferences();
showDifferencesButton.addEventListener("click", function () {
const tableBody = document.querySelector(".compare-table tbody");
const rows = tableBody.querySelectorAll(".compare-row");
let showingDifferences = this.dataset.showingDifferences !== "true";
rows.forEach((row) => {
const cells = row.querySelectorAll("td");
if (cells.length > 1) {
let allEqual = true;
const firstValue = cells[1].textContent.trim();
for (let i = 2; i < cells.length; i++) {
if (cells[i].textContent.trim() !== firstValue) {
allEqual = false;
break;
}
}
// When showing differences, hide rows where all values are equal
// When showing all, always show rows
if (showingDifferences && allEqual) {
row.style.display = "none";
} else {
row.style.display = "";
}
}
});
this.dataset.showingDifferences = showingDifferences ? "true" : "false";
this.textContent = showingDifferences
? "Show all features"
: "Show only differences";
});
});
</script>
|