I would like to create an item, that can be present in a cart only if at least one product of a specific collection is in a cart. I have checked CartBot app, but it only works with automatically added items. I have also checked some minmax limit apps, but they don’t support such behaviour.
I can create a conditional “add to cart” button on storefront, but the main issue is auto-deleting of the item if the conditions are no longer met. This could be solved by changing the delete button Javascript code, but I am wondering if there is an easier option or if someone has already solved this.
Hi,
Adding custom javascript can help .
Code example(theme.liquid)
function removeItemFromCart(itemId, callback) {
fetch('/cart/change.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
id: itemId,
quantity: 0
})
})
.then(response => response.json())
.then(data => {
if (typeof callback === 'function') {
callback(data);
}
})
.catch(error => console.error('Error:', error));
}
function handleCartUpdates() {
fetch('/cart.js')
.then(response => response.json())
.then(data => {
const cartItems = data.items;
let itemToRemove = null;
cartItems.forEach(item => {
// Add your condition to check which item should be removed
// For example, remove item B if item A is removed
if (/* condition to identify item to remove */) {
itemToRemove = item;
}
});
if (itemToRemove) {
removeItemFromCart(itemToRemove.id, (response) => {
console.log('Removed item:', response);
});
}
});
}
// Call handleCartUpdates when appropriate
document.addEventListener('DOMContentLoaded', handleCartUpdates);
This in general works (I only need to find the appropriate JS event), only one small change - Shopify is not consistent when using cart/change.js and requires variant ID as a string (not number). adding toString() to itemToRemove.id solves that.
For more see this thread: https://community.shopify.com/post/1012114