Skip to content

Instantly share code, notes, and snippets.

@Asikur22
Created April 9, 2022 14:39
Show Gist options
  • Save Asikur22/2e63fc2db497b181ce5b69d4578eabc9 to your computer and use it in GitHub Desktop.
Save Asikur22/2e63fc2db497b181ce5b69d4578eabc9 to your computer and use it in GitHub Desktop.
Shopify add and remove item from the cart
let cartBtn = document.querySelector("YOUR CART BUTTON CLASS NAME")
const form = document.getElementById("YOUR FORM ID")
form.addEventListener("submit", (e) => {
e.preventDefault()
if (cartBtn.getAttribute("data-variant-id")) {
removeItem()
}
else {
addItem()
}
})
function removeItem() {
let variantId = cartBtn.getAttribute("data-variant-id")
$.ajax({
type: 'POST',
url: '/cart/change.js',
dataType: 'json',
data: {
'id': parseFloat(variantId),
'quantity': 0
}
})
.then(data => {
cartBtn.textContent = "Add to cart"
cartBtn.removeAttribute("data-variant-id");
})
}
function addItem() {
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: $('#' + "YOUR FORM ID").serialize()
})
.then(data => {
cartBtn.textContent = "Remove from cart"
cartBtn.setAttribute("data-variant-id", data.variant_id);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment