Liquid, JavaScript, themes, sales channels
I am trying to create a add to cart button with incrementors to create a smoother experience (picture for reference).
The little box in the button should corresponded with the amount of ordered items already in the cart. This will make the experience less confusing, given that the counter will restart at a refresh. To try to achieve this I have used:
{% for item in cart.items %}
{% case item.id %}
{% when product.id %}
{{item.quantity}}
{% endcase %}
{% endfor %}
And
{% for item in cart.items %}
{% if item.id == product.id %}
{% assign quantity = item.quantity %}
{% endif %}
{% endfor %}
{%- if quantity >= 0 -%}
{{ quantity }}
{%- else -%}
0
{%- endif -%}
It seems to me that liquid is unable to compare these two variables/object data's with each other. To give a little more context, this code is placed in a snippet.
Hi.
I would use Javascript and CartJS to get the current Qty.
Here is function that will return the current qty in the cart.
Plus you could add some validation for negative and max.
function getQty(_sku) {
for (let i = 0; i < CartJS.cart.items.length; i++) {
let _item = CartJS.cart.items[i];
// console.log(_item);
if (_sku.toString() == _item.sku.toString()) {
return _item.quantity;
}
}
return 0;
}
From your snippet looks like you are code savvy so I kept it brief.
If you need further explanation let me know.
Regards,
Jon
Hi Jon,
Thanks for your tip and sorry for my late response.
I've tried to implement CartJS but get the following error: Uncaught ReferenceError: CartJS is not defined
I reckon this is because I am editing shopify's Debut theme which might not have jQuery installed. I can't quite see if either jquery or cartjs is installed in this theme and I actually rather avoid calling jQuery for this feature only, because of performance reasons. Is this the only way to do this or is there maybe a vanilla alternative to cart.js?
I might try to compare data of the order with information from the {{ cart | json }} object, but I haven't found a way to decrease the orders when - is pressed.
Here you go.
I have it in the <head> area.
<!------------------------------------------------------------------------------------------ Cart JS -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.1/cart.min.js"></script>
<script type="text/javascript">
jQuery(function () {
CartJS.init({{ cart | json }});
});
</script>
Portrait of Stephen positioned next to an image of planet Earth, with the Stephen's World ...
By JasonH Mar 18, 2024Digital marketers and app developers have tracked activity in apps and websites for yea...
By Ollie Mar 13, 2024February was an exciting month with Shopify Editions, informative webinars, and more! F...
By JasonH Mar 7, 2024