Does anyone know how to add an ‘Add to cart’ button on collection pages, such that when the users click on this button, it adds the product to the cart drawer, instead of going to the cart page? I’m using the Prestige theme, and I would really appreciate any help anyone can provide.
Hello @chloeann ,
Add this code in product-item.liquid under Snippets
Note: Make it conditional a/to your need.
Next in custom.js under Assets, add this code
$('.ad_to_cart_coll').click(function(){
var ID = $(this).attr("data-var_id");
addItemToCart( ID, 1); // paste your id product number
$('.cart_dr').trigger( "click" );
});
function addItemToCart(variant_id, qty) {
data = {
"id": variant_id,
"quantity": qty
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
bubbles: true //this code is for prestige theme, is to refresh the cart
}));
}
});
}
In same file custom.js at top you will find more details about how to enable cart drawer in on click of custom ‘add to cart’ button in collection page.
Thanks
@Guleria this solution not working open the theme cart drawer and also does not work for the non variants product
@Guleria this works up to some point, however, the issues are:
-
Clicking the button doesn’t open the cart drawer
-
There isn’t a quantity selector above the Add to Cart button
-
There isn’t padding on top so it looks really unprofessionally added
-
The button is too big - on product pages it makes sense size-wise, however, on collection no.
Could you help in making these small edits to the code, it would be incredibly appreciated by a large number of people, myself specifically!
Thank you for everything you do.
If anyone else was able to make these small edits, I’d love to see it.
- Sorry I cannot share my website.
Hello i mange to open the drawer by retrieve the header cart icon and simulate click in the js code :
function _addMeToCart(e, el) {
e = e || window.event;
e.preventDefault();
let formData = {
'items': [
{
'id': el.dataset.variant_id,
'quantity': 1
}
]
};
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then((resp) => {
return resp.json();
})
.then((data) => {
var cartDrawerButtonSelector = "Header__Icon Icon-Wrapper Icon-Wrapper--clickable ";
var cartDrawerButton = document.getElementsByClassName(cartDrawerButtonSelector)[3];
/* alternative that returns array of ALL matching elements so reference the first with [0]
var cartDrawerButton = document.getElementsByClassName('js-drawer-open-right-link')[0];
*/
console.log(cartDrawerButton);
cartDrawerButton.click();
document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
bubbles: true
}));
})
.catch((err) => {
console.error('Error: ' + err);
})
}
Hey and thanks for the code, where do I implement this and do I need to add anything to the product-item ? thanks