Is there a way to dynamically modify a text with Shopify Liquid?
I have a question related to Shopify Liquid Coding, and I'm hoping that you can help me out a little bit!
Basically, I want to have a text dynamically update when a customer increments the quantity of a product on the cart page, without the page restarting. ( Kind of, like, how the price updates on the cart page when someone increases the quantity of a product, without the page restarting.)
This is what I've done so far:
<div class="cart__footer">
{% if cart.item_count == 1 %}
<p class="grid__item text-right small--text-center">Add another item for 5% discount!</p>
{% elsif cart.item_count == 2 %}
<p class="grid__item text-right small--text-center">Add another item for 10% discount!</p>
{% elsif cart.item_count == 3 %}
<p class="grid__item text-right small--text-center">Add another item for 15% discount!</p>
{% elsif cart.item_count >= 4 %}
<p class="grid__item text-right small--text-center">Hooray! Maximum discount reached!</p>
{% endif %}
</div>
And this actually works, but only if I refresh the page.
What do you think? And ideas?
Answer
Solution:
I think what you're looking for is the Cart JS API (https://shopify.dev/api/ajax/reference/cart)
I would use thePOST /cart/add.js
method to add an item to the cart. The return value for that endpoint is a JSON object containing the current cart items, eg:
{
"items": [
{
"id": 794864229,
"quantity": 1
}
]
}
You can then read that information and update the page with the correct content using Javascript, eg:
let el = document.querySelector('.grid__item.text-right');
if(qty == 3){
el.innerHTML = "Add another item for 15% discount!"
}
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.