Rubik Variant Images & Swatch dispatches a custom JavaScript event whenever a user selects a variant option. This allows you to integrate with analytics, tracking systems, or run custom functionality when a swatch is clicked.
The event fires for all swatch types: image swatches, pill/text swatches, and dropdowns.
rubik-swatch-clicked
document.addEventListener('rubik-swatch-clicked', function(e) {
console.log('Swatch clicked:', e.detail);
});
| Property | Type | Description |
|---|---|---|
optionName |
string | The variant option category (e.g., "Color", "Size") |
optionValue |
string | The selected variant value (e.g., "Black", "40") |
optionValueId |
string|null | Shopify's identifier for the selected option value, useful for API calls |
element |
HTMLElement | The clicked DOM element (radio input or select), useful for UI modifications |
document.addEventListener('rubik-swatch-clicked', function(e) {
console.log('Swatch Clicked!', {
optionName: e.detail.optionName,
optionValue: e.detail.optionValue,
optionValueId: e.detail.optionValueId,
element: e.detail.element
});
});
document.addEventListener('rubik-swatch-clicked', function(e) {
if (window.gtag) {
gtag('event', 'swatch_click', {
option_name: e.detail.optionName,
option_value: e.detail.optionValue,
option_value_id: e.detail.optionValueId
});
}
});
document.addEventListener('rubik-swatch-clicked', function(e) {
fetch('/api/track', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
event: 'swatch_click',
option_name: e.detail.optionName,
option_value: e.detail.optionValue,
timestamp: Date.now()
})
});
});
document.addEventListener('rubik-swatch-clicked', function(e) {
// Update a custom element on your page with the selected value
var display = document.getElementById('selected-variant');
if (display) {
display.textContent = e.detail.optionName + ': ' + e.detail.optionValue;
}
});
In addition to the swatch click event, the app also dispatches a rubik-variant-id-changed
event whenever the selected variant ID changes. This is useful when you need the resolved Shopify variant ID
rather than individual option values.
document.addEventListener('rubik-variant-id-changed', function(e) {
console.log('New variant ID:', e.detail.variantId);
});
| Property | Type | Description |
|---|---|---|
variantId |
number | The Shopify variant ID for the newly selected combination |
Paste this snippet into your browser console to see all event data when clicking swatches:
document.addEventListener('rubik-swatch-clicked', function(e) {
var d = e.detail;
alert(
'Swatch Clicked!\n\n' +
'optionName: ' + d.optionName + '\n' +
'optionValue: ' + d.optionValue + '\n' +
'optionValueId: ' + d.optionValueId + '\n' +
'element: ' + d.element.tagName
);
console.log('rubik-swatch-clicked:', d);
});
bubbles: true), so you can listen on document or any parent element.optionValue and optionName are available.