All things Shopify and commerce
hey guys,
i'm using Impulse theme.
added a sticky cart on my home page.
everything works fine but the real-time update.
if i add to cart from the sticky, the cart will update only when refreshing the page, and i want it in real-time.
can someone pls help?
the code of the sticky is the following:
{% schema %}
{
"name": "Sticky Add to Cart",
"settings": []
}
{% endschema %}
<div id="sticky-cart-container" class="hidden">
<div id="sticky-cart-content">
<div id="sticky-cart-product">
<div id="product-details">
<h4 id="product-title"></h4>
<div id="product-price">
<span id="price"></span>
<span id="compare-price"></span>
</div>
</div>
</div>
<div id="sticky-cart-selectors">
<select id="product-select" aria-label="Select Product"></select>
<select id="variant-select" aria-label="Select Variant"></select>
<div id="quantity-container">
<button type="button" id="quantity-minus" aria-label="Decrease Quantity">-</button>
<input type="number" id="quantity-input" min="1" value="1" aria-label="Select Quantity">
<button type="button" id="quantity-plus" aria-label="Increase Quantity">+</button>
</div>
</div>
<button id="sticky-add-to-cart">Add to Cart</button>
</div>
</div>
<style>
#sticky-cart-container {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 1000;
background-color: #f9f9f9;
box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
border-top: 1px solid #ccc;
padding: 10px 20px;
transition: opacity 1s ease-out;
}
#sticky-cart-content {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
#sticky-cart-product {
display: flex;
align-items: center;
margin-bottom: 10px;
}
#product-image {
width: 60px;
height: 60px;
object-fit: cover;
margin-right: 10px;
}
#product-details {
display: flex;
flex-direction: column;
}
#product-title {
font-size: 16px;
margin: 0;
}
#product-reviews {
color: #f0c14b;
margin: 5px 0;
}
#product-price {
font-size: 14px;
}
#price {
color: #b12704;
font-weight: bold;
}
#compare-price {
color: #565959;
text-decoration: line-through;
margin-left: 5px;
}
#sticky-cart-selectors {
display: flex;
flex-direction: column;
width: 100%;
margin-bottom: 10px;
}
#product-select, #variant-select, #quantity-input, #sticky-add-to-cart {
width: 100%;
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
color: #333;
}
#quantity-container {
display: flex;
align-items: center;
}
#quantity-minus, #quantity-plus {
background-color: #ddd;
border: none;
padding: 10px;
cursor: pointer;
font-size: 16px;
color: #333;
}
#quantity-minus:hover, #quantity-plus:hover {
background-color: #ccc;
}
#quantity-input {
text-align: center;
padding: 10px;
width: 60px;
margin: 0 5px;
background-color: #fff;
color: #333;
}
#sticky-add-to-cart {
background-color: #ff0000;
color: #fff;
border: none;
cursor: pointer;
border-radius: 5px;
font-weight: bold;
width: 100%;
}
#sticky-add-to-cart:hover {
background-color: #cc0000;
}
.hidden {
opacity: 0;
pointer-events: none;
}
@media (min-width: 768px) {
#sticky-cart-content {
flex-direction: row;
}
#sticky-cart-selectors {
flex-direction: row;
margin-bottom: 0;
}
#product-select, #variant-select, #quantity-container {
margin-right: 10px;
margin-bottom: 0;
}
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
var productSelect = document.getElementById('product-select');
var variantSelect = document.getElementById('variant-select');
var quantityInput = document.getElementById('quantity-input');
var quantityMinus = document.getElementById('quantity-minus');
var quantityPlus = document.getElementById('quantity-plus');
var addToCartButton = document.getElementById('sticky-add-to-cart');
var stickyCartContainer = document.getElementById('sticky-cart-container');
// Fetch products from the collection
fetch('/collections/our-collection/products.json')
.then(response => response.json())
.then(data => {
data.products.forEach(product => {
var option = document.createElement('option');
option.value = product.id;
option.text = product.title;
productSelect.appendChild(option);
});
// Trigger variant selection on product change
productSelect.addEventListener('change', function() {
updateVariantSelect(data.products);
});
// Initial variant population
updateVariantSelect(data.products);
})
.catch(error => {
console.error('Error fetching products:', error);
});
function updateVariantSelect(products) {
var selectedProductId = productSelect.value;
var selectedProduct = products.find(product => product.id == selectedProductId);
if (selectedProduct) {
variantSelect.innerHTML = '';
selectedProduct.variants.forEach(variant => {
var option = document.createElement('option');
option.value = variant.id;
option.text = variant.title;
variantSelect.appendChild(option);
});
} else {
console.error('Selected product not found');
}
}
// Quantity control
quantityMinus.addEventListener('click', function() {
var currentValue = parseInt(quantityInput.value);
if (currentValue > 1) {
quantityInput.value = currentValue - 1;
}
});
quantityPlus.addEventListener('click', function() {
var currentValue = parseInt(quantityInput.value);
quantityInput.value = currentValue + 1;
});
// Add to Cart functionality
addToCartButton.addEventListener('click', function() {
var selectedVariantId = variantSelect.value;
var selectedQuantity = parseInt(quantityInput.value);
if (!selectedVariantId) {
alert('Please select a variant.');
return;
}
var formData = {
'items': [{
'id': selectedVariantId,
'quantity': selectedQuantity
}]
};
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
updateCart();
stickyCartContainer.classList.add('hidden');
setTimeout(() => {
openCartDrawer();
}, 500);
})
.catch(error => {
console.error('Error adding to cart:', error);
});
});
function updateCart() {
fetch('/cart.js')
.then(response => response.json())
.then(cart => {
// Update cart count
const cartCountElement = document.querySelector('.cart-count');
if (cartCountElement) {
cartCountElement.textContent = cart.item_count;
}
// Update cart drawer
fetch('/cart?view=ajax')
.then(response => response.text())
.then(cartHTML => {
var parser = new DOMParser();
var doc = parser.parseFromString(cartHTML, 'text/html');
var newCartItems = doc.querySelector('.cart__items');
var newCartDiscounts = doc.querySelector('.cart__discounts');
var newCartSubtotal = doc.querySelector('[data-cart-subtotal]');
var cartDrawer = document.querySelector('#CartDrawerForm');
if (cartDrawer) {
var cartItems = cartDrawer.querySelector('.cart__items');
var cartDiscounts = cartDrawer.querySelector('.cart__discounts');
var cartSubtotal = cartDrawer.querySelector('[data-cart-subtotal]');
if (cartItems && newCartItems) {
cartItems.replaceWith(newCartItems);
}
if (cartDiscounts && newCartDiscounts) {
cartDiscounts.replaceWith(newCartDiscounts);
}
if (cartSubtotal && newCartSubtotal) {
cartSubtotal.replaceWith(newCartSubtotal);
}
}
})
.catch(error => {
console.error('Error updating drawer cart:', error);
});
// Update cart total
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: cart.currency
});
let rawvalue = cart.total_price.toString();
let rawvalue2 = rawvalue.slice(0, -2) + "." + rawvalue.slice(-2);
const currentTotal = formatter.format(rawvalue2).replace('.', ',');
const cartTotalElement = document.querySelector('.cart-total');
if (cartTotalElement) {
cartTotalElement.textContent = currentTotal;
}
})
.catch(error => {
console.error('Error fetching updated cart:', error);
});
}
function openCartDrawer() {
var cartDrawer = document.querySelector('#CartDrawer');
if (cartDrawer) {
cartDrawer.classList.add('is-open');
document.body.classList.add('overflow-hidden');
}
}
document.addEventListener('mouseleave', function(e) {
if (e.clientY < 0) {
stickyCartContainer.classList.remove('hidden');
}
});
window.addEventListener('scroll', function() {
stickyCartContainer.classList.remove('hidden');
});
});
</script>
Hi @luct4u !
Is your sticky card made by theme coding only or are you using an application for this feature? If you want an easier route, I highly suggest that you use a Sticky Add to Carts application instead.
Starting a B2B store is a big undertaking that requires careful planning and execution. W...
By JasonH Sep 23, 2024By investing 30 minutes of your time, you can unlock the potential for increased sales,...
By Jacqui Sep 11, 2024We appreciate the diverse ways you participate in and engage with the Shopify Communi...
By JasonH Sep 9, 2024