Skip to main content

Example : Add to Cart Button in Autocomplete

Logic

Add an “Add to cart” button to each product

JS Code:

customization.js
function hooks() {
FastAutocomplete.registerHook('render-autocomplete-product-item', ({ product, index, element }) => {
element.querySelectorAll('[class*="addToCartBtn_autocomplete"]').forEach(e => {
e.remove()
});
if (element.querySelectorAll('.addToCartBtn_autocomplete').length == 0) {
const addToCartBtn = document.createElement("button");
addToCartBtn.innerText = "Add to bag";
element.querySelector('.fs-product-info').appendChild(addToCartBtn).classList.add("addToCartBtn_autocomplete");
let productVariant = product.s;
productVariant = productVariant.split("::").pop();
let data = {
'id': productVariant,
'quantity': 1
};
addToCartBtn.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();

fetch("https://www.nameofyoursite.com/cart/add.js", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(res => {
addToCartBtn.innerText = "Adding...";
fetch("https://www.nameofyoursite.com/cart.js", {
method: "GET",
headers: {
'Content-Type': 'application/json'
},
})
.then(response => response.json())
.then(json => {
addToCartBtn.innerText = "Added!";
document.dispatchEvent(new CustomEvent('cart:build'));
document.dispatchEvent(new CustomEvent('cart:open'));
setTimeout(() => {
addToCartBtn.innerText = "Add to bag";
}, 2000)
let item_count = json.item_count;
let cartBubble = window.document.querySelector('.cart-link__bubble');
cartBubble.classList.add('cart-link__bubble--visible');
document.dispatchEvent(new CustomEvent('cart:build'));
});
});
});
}

});
}

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

Result

image