How to Add a Product Comparison Feature to Your Shopify Website

How to Add a Product Comparison Feature to Your Shopify Website

Want to help your customers make better purchasing decisions? A product comparison feature lets shoppers compare up to 3 products side-by-side, making it easier for them to choose the right item. This comprehensive guide will show you how to add this powerful feature to your Shopify Dawn theme - no coding experience required!

What You’ll Need

  • Shopify store with Dawn theme installed
  • Access to your Shopify admin

Important: Always make a backup of your theme before making changes! Go to Online Store → Themes → Actions → Duplicate to create a backup copy.


Step 1: Create the Compare Page Template

First, let’s create the page where customers will see their product comparisons.

  1. Go to Shopify Admin → Online Store → Themes
  2. Find your Dawn theme and click Actions → Edit code
  3. Under Templates, click Add a new file
  4. Name the file page.compare.liquid
  5. Hit Enter
  6. Paste this code:
  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>
  1. Click Save

Step 2: Create the Compare Page in Shopify Admin

Now let’s create the actual page that will use our template.

  1. Go to Shopify Admin → Online Store → Pages
  2. Click Add page
  3. Title it “Compare”
  4. In the Theme template dropdown, select compare
  5. Leave the content area empty (all content is in the template)
  6. Set the handle to compare (if it’s not already set)
  7. Click Save

Step 3: Add Compare Buttons to Product Cards

Now let’s add the “Compare” buttons that customers will click on product pages.

  1. Go back to Online Store → Themes → Actions → Edit code (for your Dawn theme)
  2. Under Snippets, find and click card-product.liquid
  3. Scroll down to find where you want to add the button (a good place is after the quick-add buttons, around line 290)
  4. Add this code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<div class="compare-button-wrapper">
  <button
    class="button button--secondary compare-button"
    data-product-id="{{ card_product.id }}"
    data-product-handle="{{ card_product.handle }}"
    data-product-title="{{ card_product.title | escape }}"
    data-product-image="{{ card_product.featured_media | image_url: width: 100 }}"
  >
    Compare
  </button>
</div>
  1. Click Save

Tip: If you want to move the button location, just cut and paste this code snippet to different places in the file until you find the perfect spot!


Step 4: Add the JavaScript Functionality

This is where the real magic happens! We’ll create the JavaScript that makes everything work together.

  1. Still in the theme code editor, click Assets in the left sidebar
  2. Select Create a new file
  3. Name it compare-products.js
  4. Hit Enter on keyboard
  5. Paste this complete code:
  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
document.addEventListener("DOMContentLoaded", () => {
  const compareButtons = document.querySelectorAll(".compare-button");
  const compareBar = document.createElement("div");
  compareBar.id = "compare-bar";

  const updateCompareBarStyle = () => {
    const isMobile = window.innerWidth <= 768;
    if (isMobile) {
      compareBar.style.cssText = `
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        padding: 10px 15px;
        box-shadow: 0 -3px 10px rgba(0,0,0,0.15);
        display: flex;
        flex-direction: column;
        z-index: 1000;
        transform: translateY(100%);
        transition: transform 0.3s ease-out;
        border-top: 3px solid #007bff;
        max-height: 120px;
        overflow-y: auto;
      `;
    } else {
      compareBar.style.cssText = `
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        padding: 15px 20px;
        box-shadow: 0 -4px 15px rgba(0,0,0,0.15);
        display: flex;
        justify-content: space-between;
        align-items: center;
        z-index: 1000;
        transform: translateY(100%);
        transition: transform 0.3s ease-out;
        border-top: 3px solid #007bff;
        flex-wrap: wrap;
        gap: 10px;
        max-height: 50vh;
        overflow-y: auto;
      `;
    }
  };

  updateCompareBarStyle();
  window.addEventListener("resize", updateCompareBarStyle);
  document.body.appendChild(compareBar);

  const miniComparePopup = document.createElement("div");
  miniComparePopup.id = "mini-compare-popup";

  const updateMiniPopupPosition = () => {
    const isMobile = window.innerWidth <= 768;
    if (isMobile) {
      miniComparePopup.style.cssText = `
        position: fixed;
        bottom: 80px;
        right: 15px;
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        color: white;
        padding: 10px 15px;
        border-radius: 20px;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(0,123,255,0.3);
        z-index: 999;
        display: none;
        font-weight: bold;
        font-size: 13px;
        transition: all 0.3s ease;
        border: 2px solid white;
        min-height: 40px;
        min-width: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        touch-action: manipulation;
      `;
    } else {
      miniComparePopup.style.cssText = `
        position: fixed;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        color: white;
        padding: 12px 18px;
        border-radius: 25px;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(0,123,255,0.3);
        z-index: 999;
        display: none;
        font-weight: bold;
        font-size: 14px;
        transition: all 0.3s ease;
        border: 2px solid white;
      `;
    }
  };

  updateMiniPopupPosition();
  window.addEventListener("resize", updateMiniPopupPosition);
  document.body.appendChild(miniComparePopup);

  // Maximum number of products allowed for comparison
  const MAX_COMPARE_PRODUCTS = 3;

  let productsToCompare =
    JSON.parse(localStorage.getItem("productsToCompare")) || [];

  const updateCompareBar = () => {
    updateCompareBarStyle(); // Update bar style based on viewport
    compareBar.innerHTML = "";
    if (productsToCompare.length > 0) {
      const productList = document.createElement("div");
      const isMobileList = window.innerWidth <= 768;

      if (isMobileList) {
        // Mobile layout - horizontal scroll
        productList.style.cssText = `
          display: flex;
          gap: 8px;
          overflow-x: auto;
          -webkit-overflow-scrolling: touch;
          padding: 8px 0;
          margin: 0 -15px;
          scrollbar-width: none;
          -ms-overflow-style: none;
        `;

        // Hide scrollbar
        const style = document.createElement("style");
        style.textContent = `
          #compare-bar .product-list::-webkit-scrollbar {
            display: none;
          }
        `;
        document.head.appendChild(style);
      } else {
        // Desktop layout
        productList.style.cssText = `
          display: flex;
          gap: 10px;
          flex-wrap: wrap;
        `;
      }

      productList.className = "product-list";

      productsToCompare.forEach((product) => {
        const productElement = document.createElement("div");
        const isMobile = window.innerWidth <= 768;

        if (isMobile) {
          // Mobile layout - horizontal and more compact
          productElement.style.cssText = `
            display: flex;
            align-items: center;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 6px 8px;
            min-width: 0;
            max-width: 120px;
            background: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            position: relative;
            flex: 1;
            margin-right: 6px;
          `;

          const productImage = document.createElement("img");
          productImage.src = product.featured_image;
          productImage.alt = product.title;
          productImage.style.cssText = `
            width: 32px;
            height: 32px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 8px;
            flex-shrink: 0;
          `;
          productElement.appendChild(productImage);

          const productInfo = document.createElement("div");
          productInfo.style.cssText = `
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
          `;

          const productTitle = document.createElement("span");
          productTitle.textContent =
            product.title.length > 20
              ? product.title.substring(0, 20) + "..."
              : product.title;
          productTitle.style.cssText = `
            font-size: 12px;
            font-weight: 500;
            line-height: 1.3;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 2px;
          `;
          productInfo.appendChild(productTitle);

          const productPrice = document.createElement("span");
          if (product.price) {
            const price = (product.price / 100).toFixed(2);
            productPrice.textContent = `$${price}`;
          }
          productPrice.style.cssText = `
            font-size: 10px;
            color: #666;
            font-weight: 400;
          `;
          productInfo.appendChild(productPrice);

          productElement.appendChild(productInfo);

          const removeButton = document.createElement("button");
          removeButton.textContent = "×";
          removeButton.style.cssText = `
            position: absolute;
            top: -4px;
            right: -4px;
            background: #dc3545;
            color: white;
            border: 2px solid white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.2);
            z-index: 10;
            flex-shrink: 0;
          `;

          removeButton.addEventListener("click", (e) => {
            e.preventDefault();
            e.stopPropagation();
            productsToCompare = productsToCompare.filter(
              (p) => p.id !== product.id,
            );
            localStorage.setItem(
              "productsToCompare",
              JSON.stringify(productsToCompare),
            );
            // Re-enable the compare button on the product card
            const correspondingButton = document.querySelector(
              `.compare-button[data-product-id="${product.id}"]`,
            );
            if (correspondingButton) {
              correspondingButton.textContent = "Compare";
              correspondingButton.disabled = false;
            }
            updateCompareButtons();
            updateCompareBar();
          });
          productElement.appendChild(removeButton);
        } else {
          // Desktop layout - original horizontal style
          productElement.style.cssText = `
            display: flex;
            align-items: center;
            border: 1px solid #ccc;
            border-radius: 6px;
            padding: 8px;
            background: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
          `;

          const productImage = document.createElement("img");
          productImage.src = product.featured_image;
          productImage.alt = product.title;
          productImage.style.cssText = `
            width: 30px;
            height: 30px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 8px;
          `;
          productElement.appendChild(productImage);

          const productTitle = document.createElement("span");
          productTitle.textContent =
            product.title.length > 20
              ? product.title.substring(0, 20) + "..."
              : product.title;
          productTitle.style.cssText = `
            font-size: 13px;
            font-weight: 500;
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          `;
          productElement.appendChild(productTitle);

          const removeButton = document.createElement("button");
          removeButton.textContent = "×";
          removeButton.style.cssText = `
            margin-left: 8px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 22px;
            height: 22px;
            font-size: 12px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
          `;

          removeButton.addEventListener("click", (e) => {
            e.preventDefault();
            e.stopPropagation();
            productsToCompare = productsToCompare.filter(
              (p) => p.id !== product.id,
            );
            localStorage.setItem(
              "productsToCompare",
              JSON.stringify(productsToCompare),
            );
            // Re-enable the compare button on the product card
            const correspondingButton = document.querySelector(
              `.compare-button[data-product-id="${product.id}"]`,
            );
            if (correspondingButton) {
              correspondingButton.textContent = "Compare";
              correspondingButton.disabled = false;
            }
            updateCompareButtons();
            updateCompareBar();
          });
          productElement.appendChild(removeButton);
        }

        productList.appendChild(productElement);
      });
      compareBar.appendChild(productList);

      const actionsContainer = document.createElement("div");
      const isMobileActions = window.innerWidth <= 768;

      if (isMobileActions) {
        actionsContainer.style.cssText = `
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 8px 0 0 0;
          border-top: 1px solid #dee2e6;
          margin-top: 8px;
          gap: 8px;
        `;
      } else {
        actionsContainer.style.cssText = `
          display: flex;
          gap: 10px;
          align-items: center;
        `;
      }

      // Progress indicator
      const progressIndicator = document.createElement("span");
      progressIndicator.textContent = `${productsToCompare.length}/${MAX_COMPARE_PRODUCTS}`;
      progressIndicator.style.cssText = isMobileActions
        ? `
        font-size: 12px;
        color: #666;
        font-weight: 500;
      `
        : `
        font-size: 14px;
        color: #666;
        margin-right: 10px;
      `;
      actionsContainer.appendChild(progressIndicator);

      const compareLink = document.createElement("a");
      compareLink.href = "/pages/compare";
      compareLink.textContent = `COMPARE (${productsToCompare.length})`;
      compareLink.style.cssText = isMobileActions
        ? `
        background-color: #007bff;
        color: white;
        padding: 6px 12px;
        border-radius: 4px;
        text-decoration: none;
        font-weight: 600;
        font-size: 12px;
        flex: 1;
        text-align: center;
      `
        : `
        background-color: #007bff;
        color: white;
        padding: 8px 15px;
        border-radius: 5px;
        text-decoration: none;
        font-weight: bold;
      `;
      actionsContainer.appendChild(compareLink);

      const clearAllButton = document.createElement("button");
      clearAllButton.textContent = "Clear All";
      clearAllButton.style.cssText = isMobileActions
        ? `
        background-color: #dc3545;
        color: white;
        padding: 6px 10px;
        border-radius: 4px;
        border: none;
        cursor: pointer;
        font-size: 11px;
        font-weight: 500;
      `
        : `
        background-color: #6c757d;
        color: white;
        padding: 8px 15px;
        border-radius: 5px;
        border: none;
        cursor: pointer;
        font-size: 12px;
      `;
      clearAllButton.addEventListener("click", () => {
        productsToCompare = [];
        localStorage.setItem(
          "productsToCompare",
          JSON.stringify(productsToCompare),
        );
        updateCompareButtons();
        updateCompareBar();
      });
      actionsContainer.appendChild(clearAllButton);

      const shareButton = document.createElement("button");
      shareButton.textContent = "Share";
      shareButton.style.cssText = `
        background-color: #28a745;
        color: white;
        padding: 8px 15px;
        border-radius: 5px;
        border: none;
        cursor: pointer;
        font-size: 12px;
      `;
      shareButton.addEventListener("click", () => {
        // Create a more comprehensive URL with both IDs and handles
        const productData = productsToCompare
          .map((p) => `${p.id}:${p.handle}`)
          .join(",");
        const shareUrl = `${window.location.origin}/pages/compare?products=${productData}`;

        // Get product names for enhanced share text
        const productNames = productsToCompare.map((p) => p.title).join(", ");
        const shareText = `Check out my comparison of ${productNames}`;

        if (navigator.share) {
          navigator.share({
            title: "Product Comparison",
            text: shareText,
            url: shareUrl,
          });
        } else {
          navigator.clipboard.writeText(shareUrl);
          shareButton.textContent = "Link Copied!";
          setTimeout(() => {
            shareButton.textContent = "Share";
          }, 2000);
        }
      });
      actionsContainer.appendChild(shareButton);

      const closeButton = document.createElement("button");
      closeButton.textContent = "CLOSE";
      closeButton.style.cssText = `
        background-color: #dc3545;
        color: white;
        padding: 8px 15px;
        border-radius: 5px;
        border: none;
        cursor: pointer;
      `;
      closeButton.addEventListener("click", () => {
        compareBar.style.transform = "translateY(100%)";
        miniComparePopup.style.display = "block";
        miniComparePopup.textContent = `${productsToCompare.length} Compare`;
      });
      actionsContainer.appendChild(closeButton);
      compareBar.appendChild(actionsContainer);

      compareBar.style.transform = "translateY(0)";
      miniComparePopup.style.display = "none"; // Hide mini-popup when bar is open
    } else {
      compareBar.style.transform = "translateY(100%)";
      miniComparePopup.style.display = "none"; // Hide mini-popup if no products
    }
  };

  miniComparePopup.onclick = () => {
    miniComparePopup.style.display = "none";
    updateCompareBar(); // This will show the compare bar with existing products
  };

  compareButtons.forEach((button) => {
    const productId = button.dataset.productId;
    const productHandle = button.dataset.productHandle; // Get product handle
    const productTitle = button.dataset.productTitle;
    const productImage = button.dataset.productImage;

    const isProductInCompare = productsToCompare.some(
      (p) => p.id === productId,
    );
    if (isProductInCompare) {
      button.textContent = "✓ Compared";
      button.disabled = true;
    }

    // Check if max limit is reached and disable all other buttons
    if (
      productsToCompare.length >= MAX_COMPARE_PRODUCTS &&
      !isProductInCompare
    ) {
      button.disabled = true;
      button.textContent = "Max 3 selected";
    }

    button.addEventListener("click", () => {
      const product = {
        id: productId,
        handle: productHandle, // Store product handle
        title: productTitle,
        featured_image: productImage,
      };

      const index = productsToCompare.findIndex((p) => p.id === productId);

      if (index === -1) {
        // Check if we've reached the maximum number of products
        if (productsToCompare.length >= MAX_COMPARE_PRODUCTS) {
          alert(
            `You can only compare up to ${MAX_COMPARE_PRODUCTS} products at a time.`,
          );
          return;
        }
        productsToCompare.push(product);
        button.textContent = "✓ Compared";
        button.disabled = true;
      } else {
        productsToCompare.splice(index, 1);
        button.textContent = "Compare";
        button.disabled = false;
      }
      localStorage.setItem(
        "productsToCompare",
        JSON.stringify(productsToCompare),
      );
      updateCompareBar();
    });
  });

  // Function to update all compare buttons to reflect max limit
  const updateCompareButtons = () => {
    compareButtons.forEach((button) => {
      const productId = button.dataset.productId;
      const isProductInCompare = productsToCompare.some(
        (p) => p.id === productId,
      );

      if (isProductInCompare) {
        button.textContent = "✓ Compared";
        button.disabled = true;
      } else if (productsToCompare.length >= MAX_COMPARE_PRODUCTS) {
        button.disabled = true;
        button.textContent = "Max 3 selected";
      } else {
        button.disabled = false;
        button.textContent = "Compare";
      }
    });
  };

  updateCompareBar(); // Initial update on page load
  updateCompareButtons(); // Update button states on initial load

  // Check if products are already in localStorage on page load and show mini-popup if so
  if (productsToCompare.length > 0) {
    miniComparePopup.style.display = "block";
    miniComparePopup.textContent = `${productsToCompare.length} Compare`;
    compareBar.style.transform = "translateY(100%)"; // Ensure compare bar is hidden initially
  }

  // Add resize listener to update compare bar style on window resize
  window.addEventListener("resize", () => {
    updateCompareBarStyle();
    updateCompareBar();
  });
});
  1. Click Save

Step 5: Connect JavaScript to Your Theme

Now we need to tell your theme to use the JavaScript file we just created.

  1. In the theme code editor, under Layout, click theme.liquid
  2. Scroll down to find the closing </body> tag (it’s near the bottom)
  3. Just BEFORE the </body> tag, add this line:
1
<script src="{{ 'compare-products.js' | asset_url }}" defer="defer"></script>
  1. Click Save

You’re All Set! 🎉

Your product comparison feature is now live! Here’s what your customers can do:

Compare up to 3 products side-by-side
See real product data including prices, descriptions, and attributes
Remove products from comparison with one click
Share comparisons with others via link or social media
Works perfectly on mobile phones with responsive design
Persistent comparison - products stay selected even when browsing different pages
Show only differences toggle to highlight unique features
Add to cart directly from comparison table

How It Works for Your Customers:

  1. Browse products on your store
  2. Click “Compare” on products they want to compare (max 3)
  3. See compare bar appear at bottom of screen with product previews
  4. Click “COMPARE” button in bar to view detailed comparison table
  5. Use “Show only differences” to highlight unique features
  6. Share comparison with others or add products to cart directly
  7. Remove products as needed to make room for new comparisons

What Makes This Special:

  • Mobile-First Design: Automatically adjusts for phone screens with horizontal scrolling and touch-friendly controls
  • Smart Limits: Prevents customers from comparing too many products (max 3) for optimal experience
  • Visual Feedback: Buttons change to show when products are selected ("✓ Compared")
  • Share Functionality: Customers can share their comparisons with others

Troubleshooting

If you run into any issues, check these common solutions:

Compare Buttons Not Showing:

  • Ensure you added the button code to card-product.liquid
  • Check that the file was saved properly
  • Verify you’re using a collection or product page that displays product cards

Compare Page Not Working:

  • Make sure you created the page.compare.liquid template correctly
  • Verify the page in Shopify Admin is using the compare template
  • Check that the compare page URL is /pages/compare

JavaScript Not Loading:

  • Ensure the script tag was added to theme.liquid before </body>
  • Check that compare-products.js was saved in the Assets folder
  • Try clearing your browser cache

Your customers will love how easy it is to make informed purchasing decisions, and you’ll likely see increased conversions, higher average order values, and improved customer satisfaction!


The comparison feature should work immediately after completing these steps. For additional support, feel free to reach out via the contact form.

Happy selling!

DOUDMINE

Related Posts

Adding a Parallax Section to Your Shopify Store

Adding a Parallax Section to Your Shopify Store

A parallax section creates an engaging visual effect where the background image appears to move at a …

Read More
Implementing a Products Carousel Slider for Shopify

Implementing a Products Carousel Slider for Shopify

A product carousel slider is an effective way to showcase multiple products in a compact space, …

Read More
Displaying Custom Author Names Using Metafields

Displaying Custom Author Names Using Metafields

By default, Shopify themes display blog post authors based on staff admin accounts. However, you can …

Read More