Skip to main content

Example : Color Swatches With a Pattern File

Logic

Update the color swatches with a pattern file:

JS Code:

/* get all products to loop on */
function getProductElements(element) {
return [...element.querySelectorAll(`.fs-results-product-card`)];
}

function hooks() {

let assetUrl = "https://cdn.shopify.com/s/files/1/0642/9497/7770/files/";

window.SerpOptions.registerHook("serp-filters", ({filters, element}) => {
if(typeof element !== 'undefined' && element.querySelectorAll('.swatches').length > 0){
// color swatches images
var allColorSwatches = element.querySelectorAll(".color-swatch-container.fs-color-swatch-container");

if (allColorSwatches.length > 0){
allColorSwatches.forEach(function (swatchContainer) {
let colorName = swatchContainer.querySelector('.color-swatch-color-name').innerHTML.toLowerCase();
let swatch = swatchContainer.querySelector('.color-swatch');
swatch.style.backgroundColor = colorName;
colorName = colorName.replaceAll('/', '-')+'_50x50.png';
colorName = colorName.replaceAll(' ', '-');
colorName = colorName.replaceAll('color_', '');
colorName = assetUrl + colorName;
if(swatch.style.backgroundColor === '' || swatch.style.backgroundColor !== swatchContainer.querySelector('.color-swatch-color-name').innerHTML.toLowerCase())
{
swatch.style.backgroundImage = "url("+colorName+")";
}
});
}
}
});

window.SerpOptions.registerHook("serp-product-grid", ({products, element}) => {
for (const productElement of getProductElements(element)) {
const productID = productElement.dataset.productId;
const data = products[productID];

// color swatches images
var allColorSwatches = productElement.querySelectorAll(".color-swatch-container");

if (allColorSwatches.length > 0)
{
allColorSwatches.forEach(function (swatchContainer)
{
let colorName = swatchContainer.querySelector('.color-swatch-color-name').innerHTML.toLowerCase();
let swatch = swatchContainer.querySelector('.color-swatch');
swatch.style.backgroundColor = colorName;
colorName = colorName.replaceAll('/', '-')+'_50x50.png';
colorName = colorName.replaceAll(' ', '-');
colorName = colorName.replaceAll('color_', '');
colorName = assetUrl + colorName;
if(swatch.style.backgroundColor === '' || swatch.style.backgroundColor !== swatchContainer.querySelector('.color-swatch-color-name').innerHTML.toLowerCase())
{
swatch.style.backgroundImage = "url("+colorName+")";
}
});
}
}
});
}

if (window.SerpOptions) {
hooks();
} else {
window.addEventListener('fast-serp-ready', function () {
hooks();
});
}

Result

image