Created
April 9, 2022 14:39
-
-
Save Asikur22/2e63fc2db497b181ce5b69d4578eabc9 to your computer and use it in GitHub Desktop.
Shopify add and remove item from the cart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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