Example : Single Color Swatch Per Product
Logic
Display a single color swatch circle for each one color product.
JS Code:
function getProductElements(element) {
return [...element.querySelectorAll(.fs-results-product-card)];
}
const qsa = (root, sel) => root.querySelectorAll(sel);
const qs = (root, sel) => root.querySelector(sel);
const el = (tag, ...classes) => {
const n = document.createElement(tag);
if (classes.length) n.classList.add(...classes);
return n;
};
function addSingleColorSwatch(productElement, data) {
const hasSwatches = qsa(productElement, '.color-swatch-container').length > 0;
const color = data?.variants?.[0]?.attributes?.Color;
console.log('single swatch test', productElement, data, hasSwatches, color);
if (hasSwatches || !color) return;
const colorForClass = String(color).toLowerCase().replaceAll(' ', '_');
const swatchContainer = el('span', 'color-swatch-container', 'fs-color-swatch-container');
const colorSwatch = el(
'span',
'color-swatch',
'fast-swatch-color-fallback',
fast-swatch-color-${colorForClass},
isp-product-color-swatch${colorForClass}, // kept exactly as in your code
'fs-result-page-rybz61',
'selected'
);
// set CSS variables (more robust than mutating cssText)
colorSwatch.style.setProperty('--swatch-width', '25px');
colorSwatch.style.setProperty('--swatch-height', '25px');
const swatchesRoot = qs(productElement, '.color-swatches');
if (swatchesRoot) {
swatchesRoot.appendChild(swatchContainer);
swatchContainer.appendChild(colorSwatch);
}
}
function hooks() {
window.SerpOptions.registerHook("serp-product-grid", ({products, element}) => {
console.log(products, element);
for (const productElement of getProductElements(element)) {
/* get product data */
const productID = productElement.dataset.productId;
const data = products[productID];
// show single color swatch (fallback)
addSingleColorSwatch(productElement, data);
}
});
}
if (window.SerpOptions) {
hooks();
} else {
window.addEventListener('fast-serp-ready', function () {
hooks();
});
}