Skip to content

Instantly share code, notes, and snippets.

@Wurren
Created February 7, 2020 12:20
Show Gist options
  • Save Wurren/02ab4289c484c5df827085499a973ffd to your computer and use it in GitHub Desktop.
Save Wurren/02ab4289c484c5df827085499a973ffd to your computer and use it in GitHub Desktop.
Shopify Add to cart
document.addEventListener("DOMContentLoaded", function() {
const forms = Array.from(document.querySelectorAll("form.add_to_cart"));
forms.forEach(form => {
form.addEventListener("submit", e => {
e.preventDefault();
const button = form.querySelector("button");
const product_id = button.dataset["prod-id"];
fetch("/cart/add.js", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ quantity: 1, id: product_id });
})
.then(resp => resp.json())
.then(data => {
document.querySelector(".cart-count").textContent =
data.cart.count;
})
.catch(err => {
alert(
"Oops! Something went wrong. Please try to add your product again. If this message persists, the item may not be available."
);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment