Developer API
Optionfier exposes a lightweight event system and a global JavaScript API on the storefront. Theme developers and third-party scripts use these to react to option changes, read current selections, and integrate Optionfier data into custom UI. This page assumes you're already familiar with the merchant-facing concepts on the main docs page, in particular Appears As: Bundle Items or Text on Order.
Events
Optionfier dispatches four custom events on its mount element with bubbles: true, so you can listen at any level of the document. The mount is normally #optionfier, but it's #optionfier-byob instead when a product uses the dedicated Build-a-Box block. Listening on document sidesteps the difference, since the events bubble up regardless of which element they started on:
document.addEventListener('optionfier:change', (e) => {
console.log(e.detail);
});optionfier:init
Fires immediately when the Optionfier script loads, before any API calls or rendering. Use this to show loading indicators or prepare your UI.
Payload:
{
productId: "gid://shopify/Product/123456", // Shopify product GID
shop: "your-store.myshopify.com" // Store domain
}optionfier:loaded
Fires once after the option data has loaded from the API and the option fields have rendered on the page. Use this to hide loading indicators or initialize UI that depends on Optionfier being ready.
Payload: Full state snapshot (see State Snapshot Shape below).
optionfier:change
Fires each time a customer interacts with an option field: selecting a dropdown value, typing in a text field, picking a date, and so on. It also fires once for each successful window.Optionfier.setValue() call. It doesn't fire on system-driven changes like visibility cascading or sold-out state updates.
source tells you who made the change: "user" for a customer, "script" for a setValue() call.
Payload:
{
// What changed
optionId: "abc123",
label: "Engraving Text",
value: "Happy Birthday", // New value (null if cleared)
previousValue: "Hello World", // Previous value (null if was empty)
source: "user", // "user" or "script"
// Full state snapshot (reflects state AFTER the change)
groupId: "group_1",
groupName: "Custom Engraving Options",
productId: "gid://shopify/Product/123456",
isSoldOut: false,
options: [ /* ... */ ]
}optionfier:submit
Fires when the product form is submitted (add to cart). This event fires during the capture phase, before the theme's own bubble-phase submit handlers run. Use it for analytics tracking or last-moment validation.
Payload: Full state snapshot (see State Snapshot Shape below).
window.Optionfier.getState()
Call this function at any time after optionfier:loaded has fired to get a snapshot of the current option state.
const state = window.Optionfier?.getState();
if (state) {
console.log('Product:', state.productId);
for (const os of state.options) {
if (os.isVisible && os.value) {
console.log(`${os.label}: ${os.value}`);
}
}
}Returns undefined if called before the options have loaded (the function itself doesn't exist yet, since window.Optionfier isn't installed until load) or if Optionfier isn't present on the page. Always use optional chaining (?.) to guard against it.
A Build-a-Box block placed on a page that isn't a product page has no product to report. There, getState() returns no snapshot and none of the four events fire.
window.Optionfier.setValue()
Selects a choice on an option set through the same code a customer's tap runs. Prices, conditional options, bundle components and the optionfier:change event follow as they do for a tap. The page is up to date when the call returns, so you can submit the product form right after it. The one exception is a call made inside a listener that another setValue call triggered: the page catches up when that outer call returns. One difference: a radio button, button or grid pick fires no DOM change event on its input, so listen for optionfier:change instead.
window.Optionfier?.setValue(optionSetId, value)
// → { ok: true } or { ok: false, reason: "..." }optionSetId is an id from the snapshot's options. value takes one of three forms:
- A string: the choice's value exactly as
getState()reports it. Match that reported value, not the text on screen: a translated storefront, or a choice whose label comes from its linked variant, shows different text than the value. { id }: one choice by its id, from the option'schoicesin the snapshot. Use this when two choices can share the same value text, since a string can't tell them apart.null: clear the selection.
Like getState(), it exists once optionfier:loaded has fired. It's removed while the option block is removed or re-rendered (a theme section reload, for example), and comes back with the next optionfier:loaded, so always call it as window.Optionfier?.setValue?.(...).
const state = window.Optionfier.getState();
const size = state.options.find((o) => o.label === 'Size');
window.Optionfier.setValue(size.id, { id: size.choices[1].id });It works on dropdown, radio button, button and grid options (type "select"). It never throws. A refused call changes nothing and returns one of these reasons:
reason | Meaning |
|---|---|
unknown_option_set | No enabled option with that id |
unsupported_type | The option isn't a dropdown, radio button, button or grid option (every choice must be one), or it sits in a Build-a-Box |
hidden | The option is hidden by its condition, or is turned off for the storefront. The snapshot's isVisible only reflects conditions, so an option turned off for the storefront still reports isVisible: true |
sold_out | That choice, or the whole option, is sold out (a sold-out option refuses null too) |
quantity | Not enough stock of that choice for the quantity in the cart form |
unknown_choice | No choice has that value, or that id |
ambiguous_choice | Two or more choices share that value text. Pass { id } instead |
not_clearable | value is null but the option can't go back to nothing selected |
not_ready | The option hasn't rendered yet. This can happen right after it was revealed, or in an optionfier:loaded listener on a fast page load. Wait for the next frame (requestAnimationFrame) and try again |
invalid_value | value isn't a string, null or { id: "..." } |
error | Something unexpected went wrong (a warning is logged to the console) |
Setting the choice that's already selected (by value or by id), or null when nothing is selected, returns { ok: true }, changes nothing and fires no event. A selected choice that has since sold out still answers sold_out.
Example: pick a frame finish from the customer's size and color. The source check stops the listener from reacting to its own call. customerPickedFinish stops it from overriding a finish the customer chose themselves.
let customerPickedFinish = false;
document.addEventListener('optionfier:change', (e) => {
if (e.detail.source === 'script') return;
const byLabel = (label) => e.detail.options.find((o) => o.label === label);
const size = byLabel('Size');
const color = byLabel('Color');
const finish = byLabel('Frame finish');
if (!finish) return;
if (e.detail.optionId === finish.id) customerPickedFinish = true;
if (customerPickedFinish || !size?.value || !color?.value) return;
const pick = size.value === 'Large' && color.value === 'Black' ? 'Matte' : 'Gloss';
const result = window.Optionfier.setValue(finish.id, pick);
if (!result.ok) console.warn('Could not set frame finish:', result.reason);
});State Snapshot Shape
The optionfier:loaded, optionfier:change, and optionfier:submit events all include a state snapshot, and window.Optionfier.getState() returns the same shape.
{
groupId: "group_1", // Internal group ID
groupName: "Custom Engraving Options", // Group display name
productId: "gid://shopify/Product/123456", // Shopify product GID
isSoldOut: false, // Whether the entire group is sold out
options: [
{
id: "opt_1",
type: "select", // Option type (see table below)
label: "Frame Material",
value: "Oak", // Current selection (null if empty)
price: "10.00", // This option's price for the current selection, after quantity (null if none)
isSoldOut: false,
isVisible: true,
isRequired: true,
appearsAs: "bundle", // "bundle", "text", or "display", see below
choices: [ // "select" options only: every choice, in display order
{ id: "ch_1", value: "Oak" },
{ id: "ch_2", value: "Walnut" }
]
},
{
id: "opt_2",
type: "text",
label: "Engraving Text",
value: "Happy Birthday",
price: null,
isSoldOut: false,
isVisible: true,
isRequired: false,
appearsAs: "text"
}
]
}Reading an option's Appears as mode
appearsAs mirrors the merchant's Appears as setting. It's per option, so one product can mix bundle and text options.
"bundle": a real product priced into the cart, with Shopify tracking its inventory."text": text on the order, no price change (though a linked variant's stock may still track in the background)."display": structural content with no value. Skip these when reading customer input.
Option Type Values
The type field on each option in the snapshot maps to the following values:
| Option Type | type value |
|---|---|
| Selectable (dropdown, radio, buttons, product grid) | "select" |
| Checkbox | "checkbox" |
| Text input | "text" |
| Number input | "number" |
| Date picker | "date" |
| Time picker | "time" |
| File upload | "file" |
| Color swatches | "color-swatch" |
| Image swatches | "image-swatch" |
| Dynamic color picker | "color-picker" |
| Layout and content (heading, paragraph, divider, spacer) | "unknown" |
An entry with type: "unknown" always has appearsAs: "display" and no value. Check appearsAs rather than type if you're specifically looking for these.
Example: Live Preview Based on Selections
document.addEventListener('optionfier:change', (e) => {
const { options } = e.detail;
const color = options.find(os => os.label === 'Color')?.value;
const text = options.find(os => os.label === 'Engraving Text')?.value;
if (color) {
document.querySelector('.preview-swatch').style.backgroundColor = color;
}
if (text) {
document.querySelector('.preview-text').textContent = text;
}
});Example: Waiting for Optionfier to Load
document.addEventListener('optionfier:loaded', (e) => {
const { options } = e.detail;
const requiredCount = options.filter(os => os.isRequired).length;
console.log(`${requiredCount} required options loaded`);
// Safe to call getState() from here on
const state = window.Optionfier.getState();
});Notes
If your event listener throws, Optionfier keeps working normally: all event dispatching is wrapped in error handling. Events are silently discarded if no Optionfier mount element is present on the page.