Start learning free

LESSON 45 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Project: The Cart Panel in JavaScript

Practice

Your cart already works the right way: the cart array is the truth, and render() draws the cart from it and saves it in localStorage after every change. In this project you finish the cart panel with two new parts: a Free delivery line that shows when the total reaches $50, and an Empty cart button that asks before it empties anything.

classList.toggle takes an optional second argument. With it, the class is not flipped: it is put on when the argument is true and taken off when it is false. A button's disabled property works the same way: true means it can't be clicked. For example, on another page:

lowStock.classList.toggle("hidden", product.stock > 3);
saveButton.disabled = field.value === "";

confirm("…") opens a box with OK and Cancel and waits for the visitor. It gives back true for OK and false for Cancel:

const sure = confirm("Leave the page?");
console.log(sure); // true for OK, false for Cancel

The check opens the page, adds the Gift card ($50) and the Mug ($12), reloads, then clicks Empty cart twice: it answers Cancel the first time and OK the second. It must print, in short:

> open the page
  button: Empty cart (disabled)
> click "Add to cart" in "Gift card"
  text: Total: $50
  text: Free delivery on this order
> click "Empty cart"
  confirm: Empty the cart? -> Cancel
  text: Total: $62
> click "Empty cart"
  confirm: Empty the cart? -> OK
  text: Cart emptied
  list (empty)
  text: Total: $0
  button: Empty cart (disabled)
> reload the page
  list (empty)
  text: Total: $0

Your task: in app.js, find the Empty cart button and the Free delivery line. In render, show the line from a total of $50 and disable the button when the cart is empty. Then give the button a click listener that asks "Empty the cart?", stops on Cancel, and otherwise empties the cart, calls render and shows "Cart emptied".


Assignment
Follow the Coding Tutorial to add the Free delivery line and the Empty cart button to the cart panel, with a confirm question before the cart is emptied.


Hint
cart is a const, so you can't give it a new array: set its length to 0 instead. Call render() after emptying it, or the screen and the saved copy keep the old lines.


STEP 1 OF 9
    Ctrl + Enter to check

    Dom Cart Project in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free