Created
May 10, 2025 19:57
-
-
Save enamhasan/53deaed27254f329e3592d5cf816e9d8 to your computer and use it in GitHub Desktop.
Shopify Add to cart jQuery
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
// ==========Add to cart jquery==========// | |
document.addEventListener('DOMContentLoaded', function() { | |
document.querySelectorAll('.productAddtocartButton').forEach(function(button) { | |
button.addEventListener('click', function(e) { | |
var btnText = button.querySelector('.btn-text').innerText; | |
e.preventDefault(); var thisAvailable = this.getAttribute('data-available'); | |
var variantId = this.getAttribute('variant-id'); | |
var quantity = 1; button.querySelector('.btn-text').textContent = 'Loading...'; | |
if (thisAvailable == 'true'){ | |
fetch('/cart/add.js', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify({ | |
id: variantId, | |
quantity: quantity, | |
properties: { | |
'Product Size': 'Full' | |
} | |
}), | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
button.querySelector('.btn-text').textContent = btnText; | |
console.log('data :', data); | |
Spruce.store('drawer').productOpen = true; | |
document.body.dispatchEvent(new CustomEvent('label:modalcart:afteradditem')); | |
}) | |
.catch((error) => { | |
button.querySelector('.btn-text').textContent = btnText; | |
console.error('Error:', error); | |
}); | |
} else{ | |
button.querySelector('.btn-text').textContent = 'Sold Out'; | |
setTimeout(function() { | |
button.querySelector('.btn-text').textContent = btnText; | |
}, 3000); | |
} | |
}); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment