Skip to content
Advertisement

How to show “cart is empty” after all items have been removed using Javascript?

I am a bit stuck and hoping someone can help me, please.

Basically I have coded a shopping cart and am currently trying to get the cart to display a message saying “Cart is empty” after all of the cart items have been removed.

Everything is working ok apart from the “Cart is empty” message being re-displayed after the cart is empty.

I have tried a few things but cannot seem to get the emptyCartMessage to display when removing the last cart item.

Just for extra context my cart items each have an independent ‘remove’ button attached to them.

My code is below.

Thank you for any help, I do appreciate it!

JavaScript

Advertisement

Answer

Please remove this line const currentCartItems = document.getElementsByClassName('cart-item');

We will use this variable inside the function ‘createCartItem’ and inside ‘removeCartItem’ tha i just created. So when calling createCartItem we can always show the cart items, because this function adds new items, so the cart is not empty.

Inside remove function first we getting the count of current items, then checking if it is less or equal 0 then we hide cart.

So the final version would be.

JavaScript
Advertisement