How to Update cart drawer in Focal theme After Adding a Product in Shopify
If you’re using the Focal theme on your Shopify store, you may have noticed that the cart drawer doesn’t automatically update when a product is added. Instead of reloading the entire page, you can use JavaScript and Shopify’s AJAX API to refresh the cart dynamically.
In this guide, we’ll walk through how to update the cart drawer without a page reload whenever a product is added.
Step 1: Add Product to Cart Using AJAX (Update Cart Drawer)
To add a product to the cart, we use Shopify’s AJAX API (/cart/add.js
). Focal theme listens for certain events to update the cart drawer. By dispatching cart:update
events, we can ensure the cart updates dynamically.
Here’s a simple JavaScript snippet that does this:
var data = {
items: [{
id: variantId, // Replace with the actual variant ID
quantity: quantity // Replace with the desired quantity
}]
};
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function(response) {
document.documentElement.dispatchEvent(new CustomEvent('cart:update', { bubbles: true }));
},
error: function(xhr, status, error) {
console.log('There was an error adding the item to the cart.');
}
});
Step 2: Refresh the Cart Drawer
Focal theme listens for certain events to refresh the cart drawer. By dispatching cart:refresh
events, we can ensure the cart updates dynamically.
Here’s a simple JavaScript snippet that does this:
var data = {
items: [{
id: variantId, // Replace with the actual variant ID
quantity: quantity // Replace with the desired quantity
}]
};
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function(response) {
document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', { bubbles: true }));
},
error: function(xhr, status, error) {
console.log('There was an error adding the item to the cart.');
}
});
Step 3: Ensure Focal Theme Detects Updates
Focal theme already has built-in logic to handle cart updates when these events are triggered. If needed, you can manually call the cart drawer refresh function:
document.documentElement.dispatchEvent(new CustomEvent('cart:update', { bubbles: true }));
document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', { bubbles: true }));
Step 4: Verify the Implementation
- Open your Shopify store using the Focal theme.
- Add a product to the cart.
- Ensure the cart drawer updates automatically without a page reload.
Conclusion
By using Shopify’s AJAX API and Focal theme’s event listeners, we can dynamically update the cart drawer whenever a product is added. This enhances user experience and provides a seamless shopping journey.
Have questions or need further customisation? Let us know in the comments!