A space to discuss online store customization, theme development, and Liquid templating.
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.
<button class="atcBtn" data-atc="33112534352009">33112534352009 test btn</button>
<script>
let atcBtn = document.querySelector(".atcBtn");
atcBtn.addEventListener("click", (event) => {
let dataAtc = event.target.dataset.atc;
atcFunc(dataAtc);
});
function atcFunc(id) {
let formData = {
items: [{
id: id,
quantity: 1
}]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(() => {
// drawer initialize and open codes here !
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>
Solved! Go to the solution
This is an accepted solution.
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!
This is an accepted solution.
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