Build a Shopify theme from scratch, with Liquid · Part 4 of 6
Variants without reloads, the Cart API and a cart drawer
A variant picker that fetches the product section with option_values and swaps what changed, add to cart over /cart/add.js with bundled sections, a dialog cart drawer fed by the HTML the Cart API returns, and /cart/change.js for quantities. About 160 lines of JavaScript, none formatting a price.
By Abhishek Fouzdar
Three parts in, the theme has had three lines of JavaScript. This part adds about a hundred and sixty, and all of them do one thing: ask Shopify for HTML and put it on the page. Choosing a variant fetches the product section for the new selection and swaps the parts that changed; adding to the cart posts to the Cart API and gets the cart drawer back, already rendered, in the same response. There is no client-side price formatting, no cart state in JavaScript, no JSON of the product on the page. Part 3 built the sections, blocks and the editor.

The rule
Shopify renders Liquid on its servers and has two APIs that hand the result to the browser on demand. The Section Rendering API returns the HTML of one section for any URL: GET /products/ajrakh-cushion-cover?section_id=template--…__main is the product section, rendered for that product, as a fragment. The Cart API at /cart/add.js, /cart/change.js and friends changes the cart and returns it as JSON, and with a sections parameter it also returns up to five sections re-rendered against the new cart, in the same call.
Between them they mean the theme's JavaScript never has to know what a price looks like, how a line item is laid out or which variant is in stock. Liquid already knows; the script fetches the answer and replaces an element. Every piece of this part follows that shape.
The three pieces are custom elements, because an element that sets itself up in connectedCallback and finds its own children is the least ceremony available for "attach behaviour to this markup", and because it is what Shopify's own Dawn does, so a developer who inherits this theme has seen the pattern.
Variants without a reload
Part 2's picker is links: every option value links to the URL of the variant it leads to, and that stays. <variant-picker> wraps the fieldsets, each value link gets data-option-value-id="{{ value.id }}", and the section root gets three attributes the script reads:
<section id="MainProduct" data-section-id="{{ section.id }}" data-product-url="{{ product.url }}" data-featured-media="{{ featured.id }}">
Then the regions that depend on the variant are marked, five of them: the thumbnails (data-swap="thumbs"), the price, the picker itself, the hidden variant id input, the buy row with the button, and the stock line. On click, the script collects one option value id per fieldset, the clicked one for its own option and the currently selected one for the others, and fetches the section:
class VariantPicker extends HTMLElement {
connectedCallback() {
this.addEventListener('click', (event) => {
const link = event.target.closest('a[data-option-value-id]');
if (!link || event.metaKey || event.ctrlKey) return;
event.preventDefault();
this.select(link);
});
}
async select(link) {
const section = this.closest('[data-section-id]');
const ids = [...this.querySelectorAll('fieldset')].map((fieldset) => {
const chosen = fieldset.contains(link) ? link : fieldset.querySelector('a[aria-current="true"]');
return chosen?.dataset.optionValueId;
});
const url = `${section.dataset.productUrl}?option_values=${ids.join(',')}§ion_id=${section.dataset.sectionId}`;
section.setAttribute('aria-busy', 'true');
try {
const doc = parse(await (await fetch(url)).text());
swapRegions(section, doc);
const variantId = section.querySelector('[data-swap="variant-id"]')?.value;
if (variantId) history.replaceState({}, '', `${section.dataset.productUrl}?variant=${variantId}`);
const media = doc.querySelector('[data-section-id]')?.dataset.featuredMedia;
if (media && media !== section.dataset.featuredMedia) {
section.dataset.featuredMedia = media;
document.getElementById(`media-${media}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
} catch {
location.href = link.href;
} finally {
section.removeAttribute('aria-busy');
}
}
}
option_values is the parameter Shopify added alongside product_option_value objects: given one value id per option, it renders the page as if that combination were selected, and when the combination does not exist it falls back the same way the Liquid does. The response is the whole product section with the new selection, so swapRegions replaces each marked region with its counterpart:
function swapRegions(root, doc) {
root.querySelectorAll('[data-swap]').forEach((el) => {
const next = doc.querySelector(`[data-swap="${el.dataset.swap}"]`);
if (next) el.replaceWith(next);
});
}
That is the entire variant logic. The price, the struck-through sizes, the Sold out button and the hidden id input all come back correct because the Liquid that rendered them on page load rendered them again. The URL is updated to ?variant= so a refresh or a shared link lands on the same selection, and when the new variant has its own photo the gallery scrolls to it, which is what part 2's "What went wrong" promised.
The network log of the screenshot above, from the browser that took it:
GET 200 /products/ajrakh-cushion-cover?option_values=12029553607025,12029553672561§ion_id=template--32823316185457__main
GET 200 /products/ajrakh-cushion-cover?option_values=12029553607025,12029553705329§ion_id=template--32823316185457__main
Two clicks, two requests of about the size of the product column, no page load. The catch is the safety net: if the fetch fails, the click becomes the navigation it would have been without JavaScript.
Add to cart
<product-form> wraps the {% form 'product' %} from part 2 and takes over its submit:
class ProductForm extends HTMLElement {
connectedCallback() {
this.form = this.querySelector('form');
this.form?.addEventListener('submit', (event) => {
event.preventDefault();
this.submit();
});
}
async submit() {
const button = this.form.querySelector('[type="submit"]');
const error = this.querySelector('[data-form-error]');
const body = new FormData(this.form);
body.append('sections', cartSections().join(','));
body.append('sections_url', location.pathname);
button.disabled = true;
try {
const response = await fetch(this.dataset.addUrl, { method: 'POST', body, headers: { Accept: 'application/json' } });
const data = await response.json();
if (!response.ok) {
error.textContent = data.description ?? data.message;
error.classList.remove('hidden');
return;
}
renderCartSections(data.sections);
announce(`Added to cart: ${data.product_title}`);
document.querySelector('cart-drawer')?.open();
} finally {
button.disabled = false;
}
}
}
The form's own fields are the request: id and quantity, exactly what /cart/add would have received as a normal POST, plus two the Cart API understands. sections names the sections to render after the add, and sections_url says which page to render them in the context of. data-add-url on the element is {{ routes.cart_add_url }}.js, because routes differ per locale and the Liquid knows the right one.
A failed add is a 422 with a description written for buyers, "All 3 Rust / 20" x 20" are in your cart" and the like, which goes straight into the error paragraph. A successful one returns the line item and, under sections, the HTML of the sections asked for.
The drawer
The drawer is a section, sections/cart-drawer.liquid, rendered once from the layout:
{% sections 'footer-group' %}
{% section 'cart-drawer' %}
<div class="sr-only" aria-live="polite" data-live-region></div>
{% section %} renders a single section statically, outside any group or template, and its id is then just its filename, cart-drawer. That matters because it is the id the Cart API is asked for. The header is the other section the cart changes, and its id comes from the section group, so the header prints it on itself (data-header-section="{{ section.id }}") and the script reads it:
function cartSections() {
const header = document.querySelector('[data-header-section]')?.dataset.headerSection;
return ['cart-drawer', header].filter(Boolean);
}
function renderCartSections(sections) {
if (!sections) return;
const drawer = document.querySelector('cart-drawer');
if (sections['cart-drawer'] && drawer) {
const open = drawer.querySelector('dialog')?.open;
const next = parse(sections['cart-drawer']).querySelector('cart-drawer');
drawer.replaceChildren(...next.children);
if (open) drawer.querySelector('dialog').setAttribute('open', '');
}
const headerId = cartSections()[1];
if (headerId && sections[headerId]) {
const count = parse(sections[headerId]).querySelector('[data-cart-count]');
document.querySelector('[data-cart-count]')?.replaceWith(count);
}
}
The drawer's children are replaced wholesale with what Shopify rendered; the header is re-rendered too but only its count badge is taken from it, so the menu and logo are not touched. The markup is a <dialog>, which gives the theme a modal with focus trapping, Escape to close and a backdrop for free:
<cart-drawer data-change-url="{{ routes.cart_change_url }}.js">
<dialog id="CartDrawer" class="fixed inset-y-0 right-0 left-auto m-0 h-dvh max-h-none w-full max-w-[440px] bg-ground p-0 shadow-2xl backdrop:bg-ink/40 open:flex flex-col" aria-labelledby="CartDrawerTitle">
<div class="flex items-center justify-between px-6 h-[72px] border-b border-line shrink-0">
<h2 id="CartDrawerTitle" class="text-xl font-bold">{{ 'cart.general.title' | t }} <span class="text-ink-2 font-normal">({{ cart.item_count }})</span></h2>
<button type="button" class="icon-btn" data-drawer-close aria-label="{{ 'accessibility.close' | t }}">{% render 'icon', name: 'close' %}</button>
</div>
<ul class="flex-1 overflow-y-auto divide-y divide-line px-6" role="list" data-drawer-items>
{%- for item in cart.items -%}
<li class="grid grid-cols-[72px_1fr] gap-4 py-4" data-line="{{ forloop.index }}">
...image, title, item.variant.title, item.final_line_price...
<quantity-input class="inline-flex items-center rounded-full border border-line bg-white">
<button type="button" data-quantity-step="-1" aria-label="{{ 'cart.general.decrease' | t: title: item.product.title }}">−</button>
<input type="number" value="{{ item.quantity }}" min="0" data-quantity-input>
<button type="button" data-quantity-step="1" aria-label="{{ 'cart.general.increase' | t: title: item.product.title }}">+</button>
</quantity-input>
<button type="button" data-line-remove>{{ 'cart.general.remove' | t }}</button>
</li>
{%- endfor -%}
</ul>
<div class="shrink-0 border-t border-line p-6 flex flex-col gap-3">
<div class="flex justify-between text-lg font-semibold"><span>{{ 'cart.general.subtotal' | t }}</span><span>{{ cart.total_price | money }}</span></div>
<form action="{{ routes.cart_url }}" method="post">
<button type="submit" name="checkout" class="btn w-full">{{ 'cart.general.checkout' | t }}</button>
</form>
</div>
</dialog>
</cart-drawer>
data-line="{{ forloop.index }}" is the one-based line number /cart/change.js wants, and the Checkout button is a form posting checkout to /cart, which is how Shopify starts checkout from any theme. The <cart-drawer> element listens for the quantity buttons, the inputs and Remove, and sends each change through the same bundled-sections call:
async change(line, quantity) {
const response = await fetch(this.dataset.changeUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ line, quantity, sections: cartSections(), sections_url: location.pathname }),
});
const data = await response.json();
if (!response.ok) { /* show data.description */ return; }
renderCartSections(data.sections);
announce(`Cart updated, ${data.item_count} items`);
}
Quantity zero removes the line. The header's cart icon keeps its href="/cart" and the script intercepts the click to open the drawer, so the cart page from part 1 is still there for anyone without JavaScript, for the View cart link, and for the no-script case generally.

The slide-in is CSS only. <dialog> goes from display: none to shown, which normally cannot transition, so the stylesheet uses @starting-style and transition-behavior: allow-discrete, which modern browsers support and old ones ignore, leaving an instant open:
#CartDrawer { transition: translate 0.3s ease, overlay 0.3s allow-discrete, display 0.3s allow-discrete; translate: 100% 0; }
#CartDrawer[open] { translate: 0 0; @starting-style { translate: 100% 0; } }
The whole exchange, from the same browser session as the screenshots:
POST 200 /cart/add.js → drawer "Your cart (1)", header badge 1, live region "Added to cart: Ajrakh Cushion Cover"
POST 200 /cart/change.js → "+" pressed: "Your cart (2)", subtotal Rs. 3,000.00
POST 200 /cart/change.js → Remove: "Your cart (0)", header badge hidden
On a phone the drawer is the full width and the same markup:

Accessibility, briefly
Three things the markup does that the script relies on. The live region in the layout announces "Added to cart" and "Cart updated" to screen readers, because the drawer opening is visual. Focus moves to the drawer's close button when it opens, and <dialog> returns focus where it was on close. The stepper buttons carry labels with the product title, so "Increase quantity of Ajrakh Cushion Cover" is what is read, not "+". And while a fetch is in flight the section or dialog is aria-busy, and the Add to cart button is disabled so a double click cannot add twice.
shopify theme check
49 files inspected with no offenses found.
What went wrong
The drawer opened with a blank image. Line item thumbnails were loading: 'lazy' like every other image in the theme, and a drawer that slides in from off-screen is, at the moment it is rendered, off-screen, so the browser had not started the request when the drawer was already open. Those few images are now eager; everything else stays lazy.
framenavigated fired on a variant change in the Playwright script that checks the page, which looked like a reload until the network log showed only the section_id request. history.replaceState is a same-document navigation and the event reports it; the proof that nothing reloaded is the log, not the event count.
The variant picker needs aria-current on the selected value, which part 2 had added for accessibility and which turned out to be the state the script reads to know the other options' selections. Had it been a class, the script would have needed its own bookkeeping. Markup that says what it is tends to be markup a script can use.
Part 5 is the rest of the storefront: predictive search and the search page, pagination done properly, metafields on the product page, translations with t and a second locale, and the customer account pages.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
4 / 6- OverviewBuild a Shopify theme from scratch, with Liquid
- Part 1The anatomy of a theme, and one that renders
- Part 2Liquid on the product and collection pages
- Part 3Sections, blocks and the theme editor
- Part 4Variants without reloads, the Cart API and a cart drawer
- Part 5Search, pagination, metafields, translations and customers
- Part 6Performance, accessibility, Theme Check and publishing