Skip to main content

Example : Save xx% label

Logic

Check products if a compare price exist, yes add a save xx% label at the bottom

JS Code:

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

/* remove label */
function removeLabel(productElement) {
const label = productElement.querySelector(".my-promo-label");
if (label) {
label.remove();
}
}

/* add new label */
function addLabel(productElement, data) {
const save = Math.round((data.comparePrice - data.price) * 100 / data.comparePrice);
if (productElement.querySelectorAll(`.my-promo-labels`).length === 0) {
productElement.querySelector(".info-container").insertAdjacentHTML('beforeend', `<div class="my-promo-labels">Save ${save}%</div>`);
}
}

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];

/* clear product */
removeLabel(productElement);

/* add if comparePrice exist*/
if( parseFloat(data.comparePrice) > 0 && parseFloat(data.comparePrice) > parseFloat(data.price) ){
addLabel(productElement, data)
}
}
});
}

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

Result

image