I created a new add to cart button for a custom template, it adds the product to the cart alright, but I have to refresh the page before it appears to my cart drawer. I used a script from the cart.js file and calling this function after adding the cart, but nothing happens.
Here’s the updateCart function:
onCartUpdate() {
if (this.tagName === 'CART-DRAWER-ITEMS') {
fetch(`?section_id=cart-drawer`).then((response) => response.text()).then((responseText) => {
const html = new DOMParser().parseFromString(responseText, 'text/html');
const selectors = ['cart-drawer-items', '.cart-drawer__footer'];
for (const selector of selectors) {
const targetElement = document.querySelector(selector);
const sourceElement = html.querySelector(selector);
if (targetElement && sourceElement) {
targetElement.replaceWith(sourceElement);
}
}
}).catch((e) => {
console.error(e);
});
} else {
fetch(`${
routes.cart_url
}?section_id=main-cart-items`).then((response) => response.text()).then((responseText) => {
const html = new DOMParser().parseFromString(responseText, 'text/html');
const sourceQty = html.querySelector('cart-items');
this.innerHTML = sourceQty.innerHTML;
}).catch((e) => {
console.error(e);
});
}
}
I also tried logging the response.text(); but the result is something like this:
<div id="shopify-section-main-cart-items" class="shopify-section">
<cart-items class="gradient color-scheme-1 isolate section-main-cart-items-padding">
<div class="page-width">
<div class="title-wrapper-with-link">
<h1 class="title title--primary">Dein Warenkorb</h1>
<a href="/collections/all" class="underlined-link">Weiter shoppen</a>
</div>
<div class="cart__warnings">
<h1 class="cart__empty-text">Dein Warenkorb ist leer</h1>
<a href="/collections/all" class="button">
Weiter shoppen
</a></div>
<form action="/cart" class="cart__contents critical-hidden" method="post" id="cart">
<div class="cart__items" id="main-cart-items" data-id="main-cart-items">
<div class="js-contents"><table class="cart-items">
<caption class="visually-hidden">
Dein Warenkorb
</caption>
<thead>
<tr>
<th class="caption-with-letter-spacing" colspan="2" scope="col">
Produkt
</th>
<th class="medium-hide large-up-hide right caption-with-letter-spacing" colspan="1" scope="col">
Gesamtsumme
</th>
<th
class="cart-items__heading--wide cart-items__heading--quantity small-hide caption-with-letter-spacing"
colspan="1"
scope="col"
>
Anzahl
</th>
<th class="small-hide right caption-with-letter-spacing" colspan="1" scope="col">
Gesamtsumme
</th>
</tr>
</thead>.....
2
Answers
You need to append the new item directly in DOM after the succesfull fetch: