Scroll To TopScroll To Top
document.addEventListener("DOMContentLoaded", function () {
document.body.addEventListener("click", function (e) {
if (e.target.classList.contains("cart-remove-btn")) {
e.preventDefault();
const itemKey = e.target.closest("li").getAttribute("data-key");
if (!itemKey) return;
// Step 1: Get latest cart to find correct line number by matching key
fetch("/cart.js")
.then(res => res.json())
.then(cart => {
const lineIndex = cart.items.findIndex(i => i.key === itemKey) + 1;
if (lineIndex === 0) return;
// Step 2: Remove item using real line number
return fetch("/cart/change.js", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
line: lineIndex,
quantity: 0
})
});
})
.then(() => {
// Step 3: Re-render cart drawer
fetch(`${routes.cart_url}?section_id=cart-widget-side`)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const newCart = doc.querySelector(".cart-widget-side");
const currentCart = document.querySelector(".cart-widget-side");
if (newCart && currentCart) {
currentCart.innerHTML = newCart.innerHTML;
}
});
});
}
});
});