Discuss and resolve questions on Liquid, JavaScript, themes, sales channels, and site speed enhancements.
hey, i am currently trying to figure out how to implement a certain feature to my product page.
I got a product and 3 variants - i want 3 simple, seperate Buy buttons for each variant. If you click on the buy button the drawer cart shall open and the variant should directly be added. So far so good. I got the inspiration from the following store: Link: https://www.stonesthrow.com/store/donuts/
I first looked for an app or theme that could do that, but i didnt find any. Then i started coding it together with chatgpt. But now i am really stuck and i need some expertise.
So i managed to implement a button for each variant with the variant ids, and also i managed through javascript and the ajax API that if i click on the button the variant is added to the cart. BUT i got problems with the drawer cart. - The cart opens but is empty everytime. If i refresh the page manually the item has actually been added to the cart. I tried a lot but i am currently clueless on how to proceed any further.
If anyone has good input i would be very glad, maybe i ran in the wrong direction. i am no expert, just trying to dig myself into problems and solve them.
Here is the code i got so far:
<form class="buy-now-form" data-variant-id="496136360047"> <button type="button" class="btn">Add to Cart</button> </form> <script> document.addEventListener('DOMContentLoaded', function() { const buyNowForms = document.querySelectorAll('.buy-now-form'); buyNowForms.forEach(function(form) { form.addEventListener('click', function(event) { event.preventDefault(); const variantId = form.getAttribute('data-variant-id'); // Add the product to the cart using Shopify's AJAX API fetch('/cart/add.js', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', }, body: JSON.stringify({ id: variantId, quantity: 1, }), }) .then(response => response.json()) .then(data => { if (data.status && data.status === 422) { // Handle the case where the product can't be added console.error('Error adding product to cart:', data.message); } else { console.log('Item added to cart:', data); // Open the cart drawer after adding the item const cartDrawer = document.querySelector('cart-drawer'); if (cartDrawer) { cartDrawer.classList.add('active'); console.log('Cart drawer opened'); } // Optionally, update the cart content dynamically here if needed } }) .catch(error => { console.error('Error adding item to cart:', error); }); }); }); }); </script>
Shopify and our financial partners regularly review and update verification requiremen...
By Jacqui Mar 14, 2025Unlock the potential of marketing on your business growth with Shopify Academy's late...
By Shopify Mar 12, 2025Learn how to increase conversion rates in every stage of the customer journey by enroll...
By Shopify Mar 5, 2025