Replies: 1 comment 7 replies
-
Hello @erikwest // Function that adds the Shipping Protection product if it isn't in the cart
// and remove extra Shipping Protection products if they are more than one in the cart
function adjustShippingProtection() {
const variantId = 40934235668668; // variant ID of the Shipping Protection product
// Find the index of the Shipping Protection product in the cart
const index = liquidAjaxCart.cart.items.findIndex(lineItem => {
return lineItem.variant_id === variantId;
});
// if there is no Shipping Protection products -- lets add it
if (index === -1) {
liquidAjaxCart.add({
items: [{
id: variantId,
quantity: 1,
}]
}, {
important: true, // run the request right away
info: { custom: true } // not to run the liquid-ajax-cart:request-end again after the request
});
return;
}
// If there is more than 1 Shipping Protection product in the cart -- decrease it
if (liquidAjaxCart.cart.items[index].quantity > 1) {
liquidAjaxCart.change({
line: index,
quantity: 1
}, {
important: true, // run the request right away
info: { custom: true } // not to run the liquid-ajax-cart:request-end again after the request
});
}
}
// Run Shipping Protection adjustment on load
if (window.liquidAjaxCart?.init) adjustShippingProtection();
else document.addEventListener("liquid-ajax-cart:init", adjustShippingProtection);
// Run Shipping Protection adjustment after each successful cart change done by the user
document.addEventListener('liquid-ajax-cart:request-end', event => {
const {requestState} = event.detail;
if (requestState.responseData?.ok && !(requestState.info.custom)) adjustShippingProtection();
}) |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a working shipping protection product toggle in the cart using {{routes.cart_change_url}} and 'data-ajax-cart-request-button'
What I really need is to add this shipping protection product on load, basically acting as a shipping protection is "enabled by default".
Ideally I can use liquidAjaxCart.change(body, options) somehow instead of add to make sure quantity is always 1 on this product. If must use .add() then need to loop through cart to make sure product isn't already added.
I tried various ways with little success. Any ideas?
Prefer not having to use jquery ajax to accomplish. Thanks
Beta Was this translation helpful? Give feedback.
All reactions