Hey guys, I am currently working on a custom Button. i want to have 3 “buy now” buttons on my product page which link to different variants. so the button should work like this: Customer clicks on the button and the drawer cart opens and refreshes and shows the item in the cart.
my custom liquid works except the refreshing of the drawer cart. The item is in the cart and if i refresh the page manually it shows up but it doesnt refresh automatically. can someone help me with my liquid?
<form class="buy-now-form" data-variant-id="49613858767183">
<button type="button" class="btn">BUY VINYL</button>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
const buyNowButtons = document.querySelectorAll('.buy-now-form');
buyNowButtons.forEach(function(form) {
form.addEventListener('submit', function(event) {
event.preventDefault();
const variantId = this.getAttribute('data-variant-id');
// Use fetch API with JSON instead of FormData
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [{
id: variantId,
quantity: 1
}]
})
})
.then(response => response.json())
.then(data => {
console.log('Item added to cart:', data);
// Trigger cart refresh event
document.dispatchEvent(new CustomEvent('cart:refresh'));
// Open the cart drawer
document.dispatchEvent(new CustomEvent('cart:open'));
// If the above events don't work, try this manual approach:
const cartDrawer = document.querySelector('cart-drawer');
if (cartDrawer) {
console.log('Cart drawer found, opening drawer...');
cartDrawer.open();
// Refresh the cart content
cartDrawer.querySelector('cart-drawer-items')?.updateContents();
} else {
console.error('Cart drawer not found.');
}
})
.catch(error => {
console.error('Error adding item to cart:', error);
});
});
});
// Change button type to submit
buyNowButtons.forEach(form => {
const button = form.querySelector('.btn');
if (button) {
button.type = 'submit';
}
});
});
</script>