← Web basics: HTML, CSS and JavaScript

Project: a to-do list

Add tasks, ignore empty ones, and tick them off.

Start this lesson

A to-do list combines almost everything: reading an input, creating elements, and listening for clicks on elements that did not exist when the page loaded. When the Add button is clicked, read the text, tidy it with trim() (which removes spaces at both ends), skip it if it is empty, create an li, append it, and clear the box for the next task. To tick a task off, give each new li its own click listener that toggles a class like done.

addButton.addEventListener("click", () => {
  const text = input.value.trim();
  if (text === "") return;          // nothing to add

  const li = document.createElement("li");
  li.textContent = text;
  li.addEventListener("click", () => li.classList.toggle("done"));
  list.append(li);

  input.value = "";                 // ready for the next one
});

Each li gets its listener at the moment it is created, so every task can be ticked off independently. return inside the if stops the handler early when the box is empty.

trim() matters: without it, a task made only of spaces would be added as an invisible empty item.

Putting input.focus() at the end returns the cursor to the box, a small touch that makes the list faster to use.