Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 61 ยท Projects

Project: A Product Card Snippet with Quick Add

Build a reusable Shopify product card snippet: documented arguments, sale and sold-out badges, a second image on hover, and a quick add button using the Ajax cart API.

The product card is the most repeated piece of a storefront. It appears in collection grids, search results, recommendations, featured-collection sections and the cart upsell. If every one of those places writes its own markup, a single design change turns into a scavenger hunt. The cure is one snippet, snippets/product-card.liquid, that takes a product and a few options as arguments and renders the same card everywhere.

In this project you will design that snippet from the outside in: first the arguments it accepts, then the badges and price, then the hover image, and finally a quick add button that puts the item in the cart without leaving the page. The real theme code is shown in read-only blocks, because Liquid and the cart endpoints exist only on Shopify. Next to it you get runnable stand-ins written in JavaScript that follow exactly the same logic, so you can test the decisions (is this on sale? is it sold out? may it be quick added?) before you ship them. You should already be comfortable with snippets and the render tag, Shopify filters and the Ajax cart API.

The Liquid in this lesson targets current Online Store 2.0 themes (the {% doc %} tag and image_tag options are available in recent Liquid versions). The stand-ins never contact Shopify: they use made-up products and a fake cart server.

Design the snippet's contract first

A snippet is a function with a loose signature. Decide the inputs before you write any markup, and write them down in a {% doc %} block so the theme editor, Theme Check and other developers can see them:

LIQUID
{% doc %}
  Renders one product card.

  @param {product} product - The product to display
  @param {string} [image_sizes] - The sizes attribute for the card image
  @param {boolean} [show_quick_add] - Show the quick add button when possible
  @param {boolean} [lazy] - Lazy-load the image (false for the first row)
{% enddoc %}

Three choices in this contract are worth explaining.

  • The product is passed in, never read from a global. Inside a render snippet you cannot see outer variables anyway, and passing the object makes the same snippet work for a collection loop, a search result or a recommendation list.
  • Layout-related inputs are arguments. The card cannot know how wide its column is, so the caller passes image_sizes. A four-column grid and a two-column mobile grid need different sizes values.
  • Defaults live in the snippet. Optional arguments should have a safe default so a bare {% render 'product-card', product: product %} still works.
flowchart LR
  A["collection grid"] --> S["snippets/product-card.liquid"]
  B["search results"] --> S
  C["recommendations"] --> S
  S --> H["card markup:<br/>image, badges, title, price, quick add"]

Many callers, one snippet: a design change is made in a single file.

Badges and the price block

Badges answer a shopper's first questions at a glance: is it discounted, is it gone, is it new? Each badge is a small condition on data the product object already has:

LIQUID
{%- liquid
  assign on_sale = false
  if product.compare_at_price > product.price
    assign on_sale = true
  endif
  assign sold_out = true
  if product.available
    assign sold_out = false
  endif
-%}

product.compare_at_price is the original price and is empty when the merchant has not set one, so the comparison works only when it is a real number greater than the price. Two traps are common here:

  • A product with several variants may have a compare-at price on only some of them. product.compare_at_price describes the product as a whole, not each variant, so for mixed catalogs also look at product.compare_at_price_max and test your own products.
  • When prices differ between variants, product.price_varies is true and the card should read "From $18.00" instead of a single price.

The sale price block then reads naturally:

LIQUID
<div class="price">
  {%- if on_sale -%}
    <s class="price__compare">{{ product.compare_at_price | money }}</s>
    <span class="price__sale">{{ product.price | money }}</span>
  {%- elsif product.price_varies -%}
    <span>From {{ product.price | money }}</span>
  {%- else -%}
    <span>{{ product.price | money }}</span>
  {%- endif -%}
</div>

Money values are integers in the smallest currency unit, which is why the money filter is needed; see Money as Integers for the reasoning. The <s> element marks the old price as no longer accurate, and for screen reader users you can add visually hidden text such as "Regular price" and "Sale price" around the two values.

Finally, a "New" badge is usually driven by a tag, because tags are the one field a merchant can edit in bulk without a developer:

LIQUID
{%- if product.tags contains 'new' -%}
  <span class="badge">New</span>
{%- endif -%}

A stand-in for the badge logic

The function below is the same decision tree written in JavaScript, with products as plain objects. Prices are cents, like in Shopify. Run it, then change a product to see how the rules react.

JS Stand-in: badges and price label

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that a sold-out product never shows "Sale" or "New". That is a design rule, not a platform rule, and it lives in one place. In Liquid the equivalent of null > number is also false, which is why the first condition is safe for products with no compare-at price.

The image: responsive, lazy and a second image on hover

The card image is usually the largest element on a collection page, so it deserves care. Use image_url to pick a width and image_tag to build the <img> with a srcset:

LIQUID
{%- assign first = product.featured_media.preview_image -%}
{%- if first -%}
  {{ first
    | image_url: width: 600
    | image_tag:
      widths: '240, 360, 480, 600',
      sizes: image_sizes,
      loading: loading,
      class: 'card__img card__img--primary'
  }}
{%- endif -%}

image_tag writes width and height attributes from the image's real dimensions, which lets the browser reserve space and avoids layout shift. If the caller passes lazy: false (the first row of a grid), set loading to eager; images below the fold use lazy. The reasoning behind this is covered in Theme Performance and Core Web Vitals.

The second image on hover is a second <img> placed in the same box, hidden by default:

LIQUID
{%- assign second = product.media[1].preview_image -%}
{%- if second -%}
  {{ second
    | image_url: width: 600
    | image_tag: widths: '240, 360, 480, 600', sizes: image_sizes, loading: 'lazy', alt: '', class: 'card__img card__img--secondary' }}
{%- endif -%}
CSS
.card__media { position: relative; aspect-ratio: 4 / 5; overflow: hidden; }
.card__img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.card__img--secondary { opacity: 0; transition: opacity 0.25s; }

@media (hover: hover) {
  .card:hover .card__img--secondary,
  .card:focus-within .card__img--secondary { opacity: 1; }
}

Three details matter. The secondary image has an empty alt because it is decorative: the primary image already describes the product. The effect is wrapped in @media (hover: hover) so touch devices, which have no hover, keep the first image instead of getting stuck on the second. And the secondary image is always lazy, because most shoppers never see it. If your design wants to avoid downloading it at all on slow connections, you can instead set its src on the first hover with a small script.

Quick add: when it is safe and what it does

A quick add button adds the item to the cart straight from the grid. It is only safe when no choice is needed, so the snippet must decide when to show it:

LIQUID
{%- liquid
  assign can_quick_add = false
  if show_quick_add and product.available and product.variants.size == 1
    assign can_quick_add = true
  endif
-%}

{%- if can_quick_add -%}
  {%- form 'product', product, class: 'card__quick-add', data-quick-add: '' -%}
    <input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}">
    <button type="submit" class="button" aria-label="Add {{ product.title | escape }} to cart">
      Quick add
    </button>
  {%- endform -%}
{%- else -%}
  <a class="button" href="{{ product.url }}">Choose options</a>
{%- endif -%}

A product with several variants needs a size or color decision, so the card links to the product page instead ("Choose options"). A single-variant product can post its only variant id. Because it is a real form tag, the button works without JavaScript: the browser posts to the cart and the shopper lands on the cart page. JavaScript then upgrades it. This is the progressive enhancement pattern from The Product Form and Add to Cart.

The upgrade intercepts the submit and calls /cart/add.js:

JavaScript
document.addEventListener('submit', async (event) => {
  const form = event.target.closest('[data-quick-add]');
  if (!form) return;
  event.preventDefault();

  const button = form.querySelector('button');
  button.disabled = true;
  try {
    const response = await fetch(window.Shopify.routes.root + 'cart/add.js', {
      method: 'POST',
      body: new FormData(form),
      headers: { Accept: 'application/json' },
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.description || 'Could not add the item.');
    document.dispatchEvent(new CustomEvent('cart:updated', { detail: data }));
  } catch (error) {
    // show error.message in an aria-live region near the button
  } finally {
    button.disabled = false;
  }
});

Disabling the button while the request runs prevents double submissions, and the cart:updated event lets the cart icon and drawer refresh themselves without the card knowing they exist.

A stand-in for the quick add flow

This stand-in puts a fake cart server behind the same logic: a button lock, a JSON error with a human message (the real API answers 422 when stock is exceeded), and an event for listeners. The stock numbers are invented.

JS Stand-in: quick add with a fake cart server

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third call fails because only two units exist. The fifth call starts while the fourth is still running, so the lock ignores it (that line prints first, because the lock check is instant). In a real theme, the stock rules come from Shopify, and the cart icon listens for cart:updated as in Building a Cart Drawer.

The whole card, running

The last stand-in is a small grid of cards that applies all of the above: badges, a price block, a second image that shows on hover or keyboard focus, and a quick add that only appears for single-variant products. The images are inline SVGs so nothing is downloaded. The "cart" is a counter, and the live region announces the result.

Stand-in: product card grid with quick add

Hover the first card to see the second image, or press Tab: :focus-within shows it for keyboard users as well. The sold-out card has no active button, and the planter, which has three variants, links to its page instead of offering a quick add.

Using the snippet

With the snippet finished, every place that lists products becomes a one-liner:

LIQUID
{%- for product in collection.products -%}
  {%- liquid
    assign lazy = true
    if forloop.index <= 4
      assign lazy = false
    endif
  -%}
  <li>
    {% render 'product-card',
      product: product,
      image_sizes: '(min-width: 990px) 25vw, 50vw',
      show_quick_add: true,
      lazy: lazy
    %}
  </li>
{%- endfor -%}

The first four cards load eagerly because they are likely above the fold; the rest are lazy. Keep each card to a small, fixed number of Liquid objects and filters, since a collection page renders this snippet dozens of times (see Liquid Performance).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the card snippet receive the product as an argument instead of reading a global variable?

    A render snippet has an isolated scope, and a passed-in product makes the same snippet reusable by every caller.
  2. 2. When should the card show a quick add button instead of a Choose options link?

    With several variants the shopper must pick a size or color, so the card links to the product page. A single available variant can be posted directly.
  3. 3. Why is the hover effect for the second image wrapped in @media (hover: hover)?

    On touch screens a tap can leave the :hover state active. Restricting the effect to hover-capable devices avoids that.
  4. 4. What does disabling the quick add button while the request is running prevent?

    Each click would otherwise send another add request. Locking the control until the response arrives keeps one click equal to one add.
  5. 5. What is the correct alt text for the decorative second image?

    An empty alt tells assistive technology to skip the image. Omitting the attribute entirely would make some screen readers read the file name.

Summary

  • Put the card in one snippet with documented arguments ({% doc %}) and render it everywhere products are listed.
  • Compute badges and the price label from product data: compare-at price, availability, price_varies and tags.
  • Use image_url with image_tag for responsive, size-stable images; load the first row eagerly and the rest lazily.
  • Show a second image on hover and focus, guarded by @media (hover: hover), with an empty alt.
  • Offer quick add only for single, available variants; build it as a real form first, then upgrade it with fetch, a button lock and a cart:updated event.

Next, build the navigation that sits above these cards in Project: An Accessible Mega Menu.