Skip to content

Instantly share code, notes, and snippets.

@saadsaif97
Created June 14, 2025 00:59
Show Gist options
  • Select an option

  • Save saadsaif97/a824966a52d0cf1f5b85b525080c9bac to your computer and use it in GitHub Desktop.

Select an option

Save saadsaif97/a824966a52d0cf1f5b85b525080c9bac to your computer and use it in GitHub Desktop.
<div class="variant-swatches">
{%- for variant in card_product.variants -%}
<span
class="variant-swatch"
style="background-image: url({{ variant.featured_image | image_url: width: 200 }});"
data-variant-image="{{ variant.featured_image | image_url: width: 500 }}"
title="{{ variant.title }}">
</span>
{%- endfor -%}
</div>
@saadsaif97

saadsaif97 commented Jun 14, 2025 •

Copy link
Copy Markdown
Author

you need to add the following css in the component-card.css

.variant-swatches {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  flex-wrap: wrap;
  position: sticky;
  z-index: 20;
}

.variant-swatch {
  width: 60px;
  aspect-ratio: 1;
  border: 1px solid #ddd;
  border-radius: 6px;
  background-position: center;
  background-size: cover;
  cursor: pointer;
  transition: border-color 0.3s, transform 0.2s;
  position: relative;
}

.variant-swatch:hover {
  border-color: #333;
  transform: scale(1.05);
}

.variant-swatch[title]::after {
  content: attr(title);
  position: absolute;
  background: #000;
  color: #fff;
  top: -50%;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  white-space: nowrap;
  display: none;
  z-index: 10;
}

.variant-swatch:hover[title]::after {
  display: block;
}

@saadsaif97

saadsaif97 commented Jun 14, 2025 •

Copy link
Copy Markdown
Author

this script updates the swatch images, you can add at the bottom of theme.liquid

<script>
  function updateSwatchImage() {
    document.querySelectorAll(".variant-swatch").forEach(swatch => {
      swatch.addEventListener("mouseover", () => {
        let newImage = swatch.dataset.variantImage;
        let image = swatch.closest(".product-card-wrapper")
        .querySelector(".card__media img");
        image.removeAttribute("srcset");
        image.setAttribute("src", newImage);
      })
    })
  }
  
  document.addEventListener("CollectionGrid:updated", () => {
    updateSwatchImage();
    console.log("CollectionGrid:updated")
  })
  
  updateSwatchImage()
</script>

@saadsaif97

Copy link
Copy Markdown
Author

in facets.js you need to dispatch this event in the funciton renderProductGridContainer

document.dispatchEvent(new CustomEvent("CollectionGrid:updated"))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment