Example : Sale Badges
Logic
Add a sale badge to every product with a compare price greater than 0.
JS Code:
customization.js
function hooks() {
const badge = `<div class="my-badge">Sale</>`;
function isBadge(data){
return parseFloat(data.p_c) > 0 && parseFloat(data.p_c) > parseFloat(data.p)
}
function addBadge(element, data){
const badge = element.querySelector(".my-badge");
// 1. cleanup badge if it's no needed anymore
if(badge){
badge.remove();
}
const target = element.querySelector('.upsell-cross-sell-image-container');
// 2. check if badge needed using isBadge function + add badge
if (target && isBadge(data)){
const save = Math.round((data.p_c - data.p) * 100 / data.p_c);
target.insertAdjacentHTML("beforeend", `<div class="my-badge">${save}%</div>`)
}
}
FastRecommendationWidget.registerHook("upsell-cross-sell-products", ({element, products}) => {
const productElements = [...element.querySelectorAll(".fs-upsell-cross-sell-product")];
for (const productElement of productElements){
const productID = productElement.dataset.id;
addBadge(productElement, products[productID]);
}
});
}
if (window.FastRecommendationWidget) {
hooks();
} else {
window.addEventListener('fast-upsell-cross-sell-ready', function () {
hooks();
});
}
CSS Code:
customization.css
.my-badge{
top: 0;
left: 0;
position: absolute;
padding: 3px 5px;
background: red;
color: white;
font-weight: bold
}