document.addEventListener("DOMContentLoaded", function () {
const MAX_QTY = 15;
// 🔹 Handle Add to Cart Submission
document.body.addEventListener("submit", function (e) {
const form = e.target.closest('form[action="/cart/add"]');
if (!form) return;
e.preventDefault();
const formData = new FormData(form);
const variantId = formData.get("id");
const qtyToAdd = parseInt(formData.get("quantity")) || 1;
fetch('/cart.js')
.then(res => res.json())
.then(cart => {
const item = cart.items.find(i => i.id == variantId);
const currentQty = item ? item.quantity : 0;
const total = currentQty + qtyToAdd;
if (total > MAX_QTY) {
alert(`You can only add up to ${MAX_QTY} of this product.`);
return;
}
// Proceed with add
fetch('/cart/add.js', {
method: 'POST',
body: formData
})
.then(res => res.json())
.then(data => {
document.dispatchEvent(new CustomEvent('cart:build', {
detail: { product: data }
}));
});
});
});
// 🔹 Handle Quantity Change in Drawer
document.body.addEventListener('click', function (e) {
const plusBtn = e.target.closest('.js-qty__adjust--plus');
if (!plusBtn) return;
const qtyInput = plusBtn.parentElement.querySelector('.js-qty__num');
let currentVal = parseInt(qtyInput.value) || 0;
if (currentVal >= MAX_QTY) {
e.preventDefault();
e.stopImmediatePropagation(); // 💥 Stops Impulse’s increment logic
alert(`You can only have up to ${MAX_QTY} of this product in your cart.`);
qtyInput.value = MAX_QTY; // Reset to max in case it's been auto-increased
return false;
}
});
// 🔹 Handle Manual Input (typing directly in quantity field)
document.body.addEventListener('change', function (e) {
const input = e.target.closest('.js-qty__num');
if (!input) return;
const value = parseInt(input.value) || 0;
if (value > MAX_QTY) {
alert(`You can only have up to ${MAX_QTY} of this product in your cart.`);
input.value = MAX_QTY;
}
});
});