Skip to main content

Example : Add Badges With Logic

JS Code:


var __fast_options = { with_product_attributes: true};

const VNEXT_FOR90_TAG_NAME = "2FOR90";

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

const NewBadges = {

set: (product, productElement) => {

var $badgewapper = `<div class="fs-badges-wrapper"></div>`;

if (productElement.querySelectorAll(`.fs-badges-wrapper`).length === 0) {
productElement.querySelector(".image-wrapper").insertAdjacentHTML('afterBegin', $badgewapper);
}
const tags = product.tags;

if(NewBadges.is2FOR90(tags)) {
NewBadges.addLabel(productElement,`<span class="fs_product_text_badge_flag seller2">2 For $90</span>`);
}
},


addLabel: (productElement, promolabel ) => {
const label = productElement.querySelector(`.fs_product_text_badge_flag`);
if (label) {
label.remove();
}
productElement.querySelector(".fs-badges-wrapper").insertAdjacentHTML('afterBegin', promolabel);
},


isSoldOut: (product) => {
return ("isSoldOut" in product && product.isSoldOut)
},


is2FOR90: (tags) => {
return tags.includes(VNEXT_FOR90_TAG_NAME);
},


isOnSale: (product) => {
const originalPrice = parseFloat(product.price);
const price = parseFloat(product.comparePrice);

return price && originalPrice && originalPrice > 0 && price > 0 && price > originalPrice;
}

};


function hooks()
{
SerpOptions.registerHook('serp-product-grid', ({products, element}) => {
for (const productElement of getProductElements(element)) {
/* get product data */
const productID = productElement.dataset.productId;
const data = products[productID];
// add badges
NewBadges.set(data, productElement);
}
});
}

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

//end for Vnext

CSS Code:

    .fs_product_text_badge_flag {
font-weight: 500;
font-style: normal;
Font-size: 10px;
line-height: 10px;
border-radius: 50px;
background-color: #fff;
transform: none;
transform-origin: unset;
padding: 5px 10px;
max-height: 10px;
letter-spacing: normal;
text-align: center;
position: absolute;
left: 10px;
box-shadow: 0 0 5px #00000026;
}

.fs_product_text_badge_flag.apponly {
background-color: #7262DA;
color: #fff;
}