Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 61 ยท Products, Collections and Variants

Variants and Option Pickers

Build a Shopify variant picker: read options and variants in Liquid, handle sold-out and missing combinations, update the URL and keep the form in sync.

A mug that comes in two colors and two sizes is not four products. It is one product with four variants: Blue / 300 ml, Blue / 450 ml, Green / 300 ml and Green / 450 ml. Each variant has its own id, price, SKU, stock and (optionally) its own image. The shopper chooses by clicking options (Color, Size), and your theme has to translate those clicks into exactly one variant.

That translation sounds easy, and then real data arrives: a combination that was never created, a variant that is sold out, a product with a single "Default Title" variant, a product with three options. This lesson shows the objects Liquid gives you, the logic of a robust picker, and the extra jobs a variant change triggers (price, button, image, URL). It builds on Building the Product Page.

Product, variant and option objects are available only in Shopify's Liquid, so the theme code here is read-only and written for current Online Store 2.0 themes. The live examples use a mock product and plain JavaScript, which is also the same logic a real theme runs in the browser. Details such as the maximum number of variants change over time; check Shopify's current limits before designing around a number.

Options and variants in Liquid

A product has up to three options, each with a name and a list of values. The most useful object for rendering pickers is product.options_with_values:

LIQUID
{%- for option in product.options_with_values -%}
  <fieldset>
    <legend>{{ option.name }}</legend>
    {%- for value in option.values -%}
      <label>
        <input
          type="radio"
          name="{{ option.name }}"
          value="{{ value | escape }}"
          {% if option.selected_value == value %}checked{% endif %}
        >
        {{ value }}
      </label>
    {%- endfor -%}
  </fieldset>
{%- endfor -%}

option.name is the option's label ("Color"), option.values is the list of values and option.selected_value is the value that belongs to the currently selected variant. Newer Liquid also exposes richer option-value objects (for example swatch data when a merchant set up swatches); check the current reference for the exact properties your target stores provide.

Each variant has these commonly used properties:

Property Meaning
variant.id the number the cart needs
variant.title combined name, such as Blue / 300 ml
variant.options array of the chosen values, in option order
variant.option1, option2, option3 the same values, one by one
variant.price, variant.compare_at_price integer money in the smallest unit
variant.available true when it can be bought now
variant.sku, variant.barcode identifiers
variant.featured_media the media tied to this variant, if any

A product with no real choices still has one variant called "Default Title", and product.has_only_default_variant is true. Skip the picker entirely in that case.

flowchart TB
  P["Product: Stoneware Mug"] --> O1["Option 1: Color"]
  P --> O2["Option 2: Size"]
  O1 --> V1["Blue / 300 ml<br/>available"]
  O1 --> V2["Blue / 450 ml<br/>sold out"]
  O1 --> V3["Green / 300 ml<br/>available"]
  O1 --> V4["Green / 450 ml<br/>no variant exists"]

Options multiply into possible combinations. Only some become real variants, and only some of those can be bought.

Sold out is not the same as missing

Two different situations look alike to a shopper but are different in the data:

  • Sold out: the variant exists, available is false. Show it, but mark it and disable the button.
  • Does not exist: nobody created that combination (Green / 450 ml above). No variant, no id, nothing to add to the cart.

A good picker tells the difference. Many themes show a sold-out value with a strikethrough and a missing value as unavailable or hidden, and both disable the add-to-cart button. A common mistake is to treat "no match found" as an error and show a blank price. Plan for it: the lookup returns undefined, and the interface says "This combination is unavailable".

Getting the data to JavaScript

Server-rendered Liquid cannot react to a click, so the page needs the variants in JavaScript. The standard approach is to print them once as JSON:

LIQUID
<script type="application/json" id="product-variants">
  {{ product.variants | json }}
</script>

Liquid's json filter makes a safe JSON string for this purpose (it escapes characters that could close the script tag early). Your script reads it:

JavaScript
const variants = JSON.parse(document.getElementById('product-variants').textContent);

Do not make a network request for data you already have on the page. If the variants list is huge, print only the fields you need, which also keeps the page light (see Liquid Performance).

The lookup logic

The whole picker boils down to three small functions:

  1. find the variant whose options array equals the current selection;
  2. compute the state of each option value: given the other current selections, would choosing this value give an available variant, a sold-out one, or none;
  3. apply the result to the page.

Step 2 is what produces the helpful behavior of dimming values that cannot be bought with the current choices. For each value of option i, copy the selection, replace position i with that value, and look up the result.

What a variant change must update

When the matching variant changes, several things must change together:

  • the hidden id input in the product form (otherwise the wrong item is added);
  • the price and compare-at price;
  • the button text and disabled state;
  • the gallery: show variant.featured_media if it has one (more in Product Media);
  • the URL, so a reload or shared link keeps the choice.

Update the URL without reloading the page using the History API:

JavaScript
const url = new URL(window.location.href);
url.searchParams.set('variant', variant.id);
window.history.replaceState({}, '', url);

replaceState overwrites the current history entry; pushState would add one per click and make the Back button annoying. On the next full page load, Liquid reads ?variant= and selected_or_first_available_variant returns that variant, so the server-rendered page matches.

Instead of rewriting every part by hand, many themes ask Shopify for freshly rendered HTML for the new variant and swap it into the page. That technique is the Section Rendering API, and it keeps Liquid as the single source of truth for markup.

A no-JavaScript fallback

Progressive enhancement means the page still works if scripts fail. A simple fallback is a plain <select name="id"> inside the product form listing every variant, with sold-out ones disabled:

LIQUID
<select name="id">
  {%- for variant in product.variants -%}
    <option value="{{ variant.id }}" {% unless variant.available %}disabled{% endunless %} {% if variant == current_variant %}selected{% endif %}>
      {{ variant.title }} - {{ variant.price | money }}
    </option>
  {%- endfor -%}
</select>

Your JavaScript can hide this and replace it with nicer radio buttons or swatches, but the form still submits a valid variant id.

Swatches and combined listings

Swatches show a color circle or image instead of text. The simplest implementation maps the value name to a CSS color, or reads swatch data when your target stores define it. Whatever the source, keep the visible text label (or an accessible name via aria-label), because color alone is not accessible. For radios, hide the input visually but keep it focusable.

Combined listings are a way to present several separate products (for example a shirt in different colors, each its own product page) as options of one family. In such a theme, an option value can link to a sibling product's page instead of changing a variant on the same page. This is a newer feature, so check the current documentation and test with real data before building for it.

Stand-in: the lookup and availability matrix

The first stand-in runs the three functions on plain data and prints a table of every combination. It shows exactly the three states a picker needs to tell apart.

JS Stand-in: variant lookup and availability

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

No output.

Notice that choosing Green while 300 ml is selected is fine, but choosing 450 ml while Blue is selected leads to a sold-out variant, and Green plus 450 ml does not exist. The picker uses exactly this information to dim values.

Stand-in: a live variant picker

The second stand-in is a small working picker in the browser. It follows the structure of a real theme script: data first, a lookup, an update() function that applies the result to the page. It does not use a real Shopify store, so the "cart" is only a status line and the URL is not changed (the preview sandbox has no history access).

Stand-in: variant picker

Try choosing Green, then 450 ml. The result panel shows that combination does not exist and the button is disabled. In a real theme the update function would also set the hidden id input, swap the gallery image and call history.replaceState. If you want a fully working add to cart, continue with The Product Form and Add to Cart.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A shopper picks Green / 450 ml, but no such variant was ever created. What should the picker do?

    There is no variant, so there is no id and no price. Tell the shopper the combination is unavailable and keep the button disabled.
  2. 2. Which input actually decides what is added to the cart?

    Carts contain variants. The form posts the variant id, so JavaScript must keep that input in sync with the selection.
  3. 3. Why use history.replaceState instead of pushState when the variant changes?

    replaceState overwrites the current entry, so the link stays shareable while the Back button still leaves the product page in one step.
  4. 4. How can product variants be handed to JavaScript without an extra request?

    The variants are already available in Liquid, so printing them as JSON once is cheaper than fetching them again.

Summary

  • A product has up to three options; each real combination is a variant with its own id, price and availability.
  • product.options_with_values renders the pickers; variant.options lets you match a selection to a variant.
  • Distinguish a sold-out variant from a combination that does not exist, and handle both without errors.
  • On every variant change update the hidden id, price, button, media and URL (replaceState).
  • Keep a plain select inside the form as a fallback, and give swatches accessible text.

Next, learn how to show the product's images, video and 3D models properly in Product Media: Images, Video and 3D.