Sikau

Project: A JavaScript app · Day 4 · about 40 min

Bring it to the page

Render the menu with the DOM and update totals on click.

From console to screen

Your functions and Cart work. Now connect them to a page: build list items from the menu, listen for clicks, and keep the total on screen in sync with the cart — one source of truth (the cart), and a function that shows it.

Render and listen

const cart = new Cart();
const menuList = document.querySelector("#menu");

function showTotals() {
  document.querySelector("#total").textContent = formatRs(cart.total());
  document.querySelector("#count").textContent = cart.count;
}

for (const item of MENU) {
  const li = document.createElement("li");
  const name = document.createElement("span");
  name.textContent = `${item.name} — ${formatRs(item.price)}`;
  const button = document.createElement("button");
  button.textContent = "Add";
  button.dataset.id = item.id;
  li.append(name, button);
  menuList.append(li);
}

menuList.addEventListener("click", (event) => {
  const id = event.target.dataset.id;
  if (!id) return;
  cart.add(id);
  showTotals();
});

document.querySelector("#clear").addEventListener("click", () => {
  cart.clear();
  showTotals();
});

The rest of this lesson

  • Connecting logic to the pageexplain
  • Keeping the screen in syncexplain
  • Where does the click land?predict
  • One clickorder
  • Make the menu clickablewrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 6 lessons of Project: A JavaScript app