Below is the code with which I can add the product to the cart when any button I have added as custom is clicked. However, I also want to open the drawer in Shopify Dawn theme. I’m stuck here.
Below is the code with which I can add the product to the cart when any button I have added as custom is clicked. However, I also want to open the drawer in Shopify Dawn theme. I’m stuck here.
Hi @ersen
In Dawn theme, you can refer to the below code for adding product to cart and trigger Drawer
const cartObject = document.querySelector('cart-notification') || document.querySelector('cart-drawer')
let formData = new FormData();
formData.append('items[][id]', '41465756221608'); // REPLACE BY YOUR ID
formData.append('items[][quantity]', '1'); // REPLACE BY YOUR QUANTITY
// Append to Cart object, used for renderContents
if (cartObject) {
formData.append(
'sections',
cartObject.getSectionsToRender().map((section) => section.id)
);
formData.append('sections_url', window.location.pathname);
}
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (!cartObject) return
cartObject.classList.remove('is-empty')
cartObject.renderContents(data)
})
.catch((error) => {
console.error('Error:', error);
});
Hope this helps!
I didn’t expect an answer so soon. thanks