Created
February 7, 2020 12:20
-
-
Save Wurren/02ab4289c484c5df827085499a973ffd to your computer and use it in GitHub Desktop.
Shopify Add to 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
| 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