Skip to main content
Tutorial4 min read

How to Add a Product Comparison Feature to Your Shopify Website

Learn how to add a product comparison feature to your Shopify dawn theme (Complete Guide)

Driss OUDMINE
Driss OUDMINE
Shopify Theme & App Developer · hello@doudmine.com
How to Add a Product Comparison Feature to Your Shopify Website
Figure 1: Production architecture diagram for tutorial optimization
Executive Summary & Key Architectural Rules
  • Shopify store with Dawn theme installed
  • Access to your Shopify admin
  • Go to Shopify Admin → Online Store → Themes
  • Find your Dawn theme and click Actions → Edit code
  • Under Templates, click Add a new file

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!

In e-commerce, every 100 milliseconds of latency during the checkout transition directly reduces conversion probability by up to 7%. Code written natively for the Liquid runtime always beats client-side script injections.

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.

Go to Shopify Admin → Online Store → Themes Find your Dawn theme and click Actions → Edit code Under Templates, click Add a new file Name the file page.compare.liquid Hit Enter Paste this code:

Step 2: Create the Compare Page in Shopify Admin

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

Go to Shopify Admin → Online Store → Pages Click Add page Title it "Compare" In the Theme template dropdown, select compare Leave the content area empty (all content is in the template) Set the handle to compare (if it's not already set) Click Save

Step 3: Add Compare Buttons to Product Cards

Now let's add the "Compare" buttons that customers will click on product pages.

Go back to Online Store → Themes → Actions → Edit code (for your Dawn theme) Under Snippets, find and click card-product.liquid Scroll down to find where you want to add the button (a good place is after the quick-add buttons, around line 290) Add this code:

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.

Still in the theme code editor, click Assets in the left sidebar Select Create a new file Name it compare-products.js Hit Enter on keyboard Paste this complete code:

Step 5: Connect JavaScript to Your Theme

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

In the theme code editor, under Layout, click theme.liquid Scroll down to find the closing </body> tag (it's near the bottom) Just BEFORE the </body> tag, add this line:

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:

Browse products on your store Click "Compare" on products they want to compare (max 3) See compare bar appear at bottom of screen with product previews Click "COMPARE" button in bar to view detailed comparison table Use "Show only differences" to highlight unique features Share comparison with others or add products to cart directly 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

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.

Implementation Snippets (4)

Drop these directly into your Shopify theme, in the order shown.

Complete code from the tutorial
section.liquid
<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>
section-2.liquid
<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>
script.js
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();
  });
});
section-3.liquid
<script src="{{ 'compare-products.js' | asset_url }}" defer="defer"></script>

Pre-Deployment Safety Checklist for Shopify Merchants

1.Always duplicate your live theme to create a staging preview before editing Liquid snippets.
2.Test all checkout progression hooks with test credit card credentials in sandbox mode.
3.Audit your Core Web Vitals on Google PageSpeed Insights after deploying to verify 0 layout shifts.
Driss OUDMINE
Written by

Driss OUDMINE

Shopify Theme & App Developer specializing in Online Store 2.0 themes, custom Shopify apps, Shopify APIs (GraphQL/REST), and store speed optimization. Not available for new opportunities at this moment.

hello@doudmine.com
Previous Article
Implementing a Products Carousel Slider for Shopify
Next Article
Adobe XD Design Assets: Wedding & Restaurant UI Templates Shared by the Community
Get in Touch · Full-Time Roles

Let's discuss how I can contribute to your team.

I am not available for new opportunities at this moment. You can still reach out for general questions about my work and articles.

Direct Email

hello@doudmine.com
One-click clipboard copy:

Candidate Snapshot:

Fast Response (Within 24 Hours)

I personally monitor my inbox and respond to technical recruiters and engineering managers promptly.

Work Authorization & Setup

Ready for remote full-time employment via Deel, Oyster, Remote.com, or direct employment.

Flexible Notice Period

Able to join team sprints within 1–2 weeks upon agreement.