Learn/HTML, CSS & JS/8. Project, a to-do list
Lesson 8 of 8
Sign in

HTML, CSS & JS, lesson 8

Project, a to-do list

Time to put the pieces together. A to-do list uses everything from this course: a form to collect text, JavaScript to create elements, events to react, and CSS to show state.

Creating elements

So far you changed elements that already existed. You can also make new ones:

createElement builds an element that isn't on the page yet; append puts it inside another.

Handling the form

Trimming and ignoring empty input are small details that make an app feel solid.

State in the page

You can keep state in CSS classes. Toggle a done class on click, and let CSS draw it:

To count unfinished tasks, select the items that don't have the class: document.querySelectorAll("#list li:not(.done)").length.

Further reading

  • MDN:

One exercise to try what you just read.

Exercise 1

To-do list

Press Ctrl Enter or Check to test your code.

Document.createElement()
  • MDN: Sending form data
  • Make the to-do list work:

    1. Submitting #todo-form adds an <li> with the (trimmed) input text to #list, then clears #todo-input. Empty or whitespace-only input adds nothing.
    2. Clicking a list item toggles the class done on it.
    3. #remaining always shows how many items do not have the class done.
    const li = document.createElement("li");
    li.textContent = "Buy flour";
    document.querySelector("#list").append(li);
    const form = document.querySelector("#todo-form");
    const input = document.querySelector("#todo-input");
    
    form.addEventListener("submit", (event) => {
      event.preventDefault();           // stay on this page
      const text = input.value.trim();
      if (!text) return;                // ignore empty tasks
      // …create the list item…
      input.value = "";                 // ready for the next one
    });
    .done {
      text-decoration: line-through;
      opacity: 0.6;
    }