Example : Add tag based label (Shopify)
Logic
Check products if tag Promo exist, if exist add a promo label at the bottom of the product
JS Code:
const PROMO_LABELS = {
'Women Sale': 'Sale!!'
}
/* search for product promos in the tags */
function getProductPromos(tags) {
return tags.reduce((promos, tag) => {
if (tag in PROMO_LABELS) {
promos.push(PROMO_LABELS[tag]);
}
return promos;
}, [])
}
/* get all products to loop on */
function getProductElements(element) {
return [...element.querySelectorAll(`.fs-results-product-card`)];
}
/* remove promo container */
function removePromo(productElement) {
const container = productElement.querySelector(".my-promo-labels");
if (container) {
container.remove();
}
}
/* add new promo label, if container is missing add it */
function addPromo(productElement, value) {
let container = productElement.querySelector(".my-promo-labels");
if (!container) {
productElement.querySelector(".info-container").insertAdjacentHTML('afterend', `<div class="my-promo-labels"></div>`);
container = productElement.querySelector(".my-promo-labels");
}
container.insertAdjacentHTML("beforeend", `<label class="my-promo-label ${value.toLowerCase()}" >${value}</label>`)
}
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 {tags} = products[productID];
/* get promos from tags (if tags exist)*/
const promos = tags ? getProductPromos(tags) : [];
/* clear product - necessary to avoid duplicated / old data */
removePromo(productElement);
/* for every promo add a label*/
for (const promo of promos) {
addPromo(productElement, promo);
}
}
});
}
// execution here
if (window.SerpOptions) {
hooks();
} else {
window.addEventListener('fast-serp-ready', function () {
hooks();
});
}