Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 156 ยท Projects

Project: To-Do App

Build a complete to-do app in plain JavaScript, step by step - state and rendering, adding, completing, filtering, editing and keyboard shortcuts.

Time to build something real. In this project you will write a to-do app from scratch with plain JavaScript โ€” no frameworks, no libraries. It is a classic first project for good reason: it is small enough to finish in one sitting, but it touches almost everything a real interface needs. You will keep data in an array, draw the page from that data, react to clicks and key presses, filter lists and edit items in place.

You will build it in six stages. Each stage is a complete, runnable example that adds one feature to the previous one, so you can run it, read the new code and experiment before moving on. The final stage is the finished app.

What you'll build

The finished app lets you:

  • add tasks with a form (press Enter or click Add);
  • tick tasks off and delete them;
  • filter by All, Active and Done, with a "tasks left" counter;
  • clear all finished tasks at once;
  • edit a task by double-clicking it (or with the keyboard), with Enter to save and Escape to cancel;
  • press / anywhere to jump to the new-task field.

Along the way you will use these lessons: Creating and Removing Elements, Events, Bubbling, Capturing and Delegation, Working with Forms, map, filter, reduce and forEach and Spread and Rest.

The big idea: state, then render

Beginners often change the page directly: when a task is added, create an <li>; when it is ticked, find the right <li> and add a class; when the filter changes, hide some itemsโ€ฆ Soon the page and your data disagree, and bugs creep in.

This app uses a simpler, sturdier approach that frameworks also use:

  1. Keep all the important data โ€” the state โ€” in plain JavaScript variables.
  2. Write one render() function that builds the page from the state.
  3. Every event handler only changes the state, then calls render().

The page becomes a picture of your data. You never have to ask "what is on screen right now?" โ€” you just look at the array.

Step 1: The page and its styles

Start with the HTML and CSS only. The three list items are hard-coded for now, so you can see the final look before writing any JavaScript.

Step 1: Markup and styles

A few details worth noticing:

  • The input has a real <label>, visually hidden with a class but still read by screen readers.
  • The Add button has no type, so it is a submit button โ€” pressing Enter in the field submits the form for free.
  • overflow-wrap: anywhere stops a very long task from breaking the layout.

Step 2: State and rendering

Now replace the hard-coded items with data. Each task is an object with an id, its text and a done flag. renderTodo() turns one object into an <li>, and render() draws the whole list with replaceChildren(), which removes the old items and inserts the new ones in a single call.

Step 2: Render the list from an array

Two choices here protect you later:

  • Each <li> stores its task's id in a data-id attribute. When the user clicks inside it, you can find the matching object in the array.
  • The task text goes in with textContent. Users can type anything, including <img onerror=โ€ฆ>, and textContent shows it as harmless text.

Step 3: Adding tasks

Listen for the form's submit event. Call preventDefault() so the page doesn't reload, read and trim the value, ignore empty input, then add to the state and re-render. A counter, nextId, gives each task a unique id.

Step 3: Add new tasks

Notice todos = [...todos, newTask] instead of todos.push(newTask). Both work here, but creating a new array each time is a good habit: it makes changes easy to spot and is exactly how state works in frameworks like React.

Step 4: Completing and deleting tasks

You could attach a listener to every checkbox and every delete button. But the list is redrawn on each change, so you would keep re-attaching them. Event delegation is simpler: one listener on the <ul> catches events that bubble up from any item, including items created later. event.target.closest("li") finds the item, and its data-id finds the task.

Step 4: Toggle and delete with delegation

The two state changes are classic array patterns:

  • Toggle: map() returns a new array where the matching task is replaced by a copy with done flipped ({ ...t, done: !t.done }), and all others stay as they are.
  • Delete: filter() keeps every task except the one with that id.

Note that data-id values are always strings, so idOf() converts with Number() before comparing with ===.

Step 5: Filters, a counter and "Clear done"

Filters are just more state. A filter variable holds "all", "active" or "done", and an object maps each name to a test function. render() shows only the tasks that pass, updates the counter, and marks the active filter button with aria-pressed (which the CSS also uses for styling). When a filter has nothing to show, a friendly message appears instead of an empty box.

Step 5: Filtering and counting

The filters object is a lookup table of functions, a pattern from Higher-Order Functions. Adding a new filter โ€” say, "starred" โ€” means adding one entry, with no new if statements.

render() now does more, but every handler stayed tiny. That is the payoff of state-then-render: features add to render() once instead of being sprinkled across every handler.

Step 6: Editing and keyboard support โ€” the finished app

The last feature is editing a task in place. Double-clicking a task's text swaps the <span> for an <input>. Enter or clicking elsewhere saves; Escape cancels. A finished flag makes sure a task is saved only once, even if both the key press and the blur event fire.

A mouse-only feature leaves keyboard users out, so the text is also focusable (tabindex="0"): tab to a task and press Enter or F2 to edit it. Finally, a global shortcut: press / anywhere (except while typing) to jump to the new-task field.

Step 6: The complete to-do app

The state changes now live in four small, named functions โ€” addTodo(), toggleTodo(), renameTodo() and deleteTodo(). The event handlers read like sentences: "toggle this task, then render." If you later add a server or storage, those four functions are the only places that need to know.

The ?.focus() after editing uses optional chaining: if the edited task is no longer visible under the current filter, there is nothing to focus, and nothing breaks.

Extension: remember tasks between visits

Right now the tasks vanish when you reload. In a normal web page you would save them with localStorage. The TryIt sandbox blocks storage, so this part can't run here โ€” but it is only a few lines in your own project (see localStorage and sessionStorage):

JavaScript
const STORAGE_KEY = "todo-app";

// On start-up: load saved tasks, falling back to an empty list
function load() {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
    if (Array.isArray(saved)) {
      todos = saved;
      nextId = Math.max(0, ...todos.map((t) => t.id)) + 1;
    }
  } catch {
    // storage unavailable or data corrupted: start fresh
  }
}

// At the end of render(): save the current state
function save() {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
  } catch {
    // storage full or blocked: the app still works, it just won't remember
  }
}

Because every change already goes through render(), calling save() there covers every feature at once โ€” one more reward for the state-then-render design.

More ideas to try

  • Show the total and finished counts in the page title with document.title.
  • Add a due date with <input type="date"> and sort by it using toSorted().
  • Let users reorder tasks with "move up" and "move down" buttons.
  • Add "Mark all as done" โ€” one map() call.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the state-then-render pattern, what should an event handler do?

    Handlers only change the data. render() turns the data into the page, so the two can never disagree.
  2. 2. Why does the app use one click listener on the <ul> instead of one per delete button?

    Events bubble up to the list. Because items are re-created on every render, delegation avoids re-attaching listeners.
  3. 3. What does todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)) do?

    map() keeps each task as it is, except the one with the matching id, which is replaced by a copy with done inverted.
  4. 4. Why is the task text inserted with textContent?

    User input inserted with innerHTML could contain HTML that runs script (XSS). textContent is always safe.
  5. 5. Why does the edit code use a finished flag?

    Saving re-renders the list and removes the input, which can fire a blur. The flag makes finish() run only once.

Summary

  • Keep data in state variables, draw the page with a single render() function, and make handlers update state then re-render.
  • Build items with createElement() and textContent, and store ids in data-* attributes to link elements to data.
  • Use event delegation on the list for toggling, deleting and editing items that are re-created on every render.
  • Array methods do the state work: spread to add, map() to change one item, filter() to delete and to apply view filters.
  • Support the keyboard: real form submission, focusable items, Enter/Escape while editing and a / shortcut.

Next: Project: Quiz Game โ€” screens, a countdown timer and scoring.