Reading history

JavaScript Project: Build a To-Do List App with localStorage

7 min read 0 views

Build a to-do list app in JavaScript: state and render, adding, completing, deleting and filtering tasks, event delegation and saving with localStorage.

A to-do list is the classic first JavaScript application because it touches everything a real app needs: reading input, keeping data in memory, drawing it on the page, reacting to clicks and remembering it for next time. In this project you will build one with adding, ticking off, deleting and filtering tasks, and save it in the browser with localStorage. The code is organised around one simple idea: change the data, then redraw from it.

In this project you will practise

  • Keeping the app’s state in an array of objects
  • A single render() function that builds the list from state
  • Form submit handling and input checks
  • Event delegation for buttons inside the list
  • Saving and loading with localStorage and JSON

The Finished App

Result

Add a task, tick it, delete it and try the filters. In this preview frame the browser blocks storage, so tasks reset when you reload; on your own page they are saved.

The Complete Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>To-Do List</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 0; background: #eceff1; }
    .app { max-width: 420px; margin: 12px auto; background: #fff; border-radius: 10px; padding: 16px;
           box-shadow: 0 4px 12px rgba(0,0,0,.1); }
    h1 { margin: 0 0 10px; font-size: 22px; }
    form { display: flex; gap: 6px; }
    #new { flex: 1; padding: 8px; font-size: 15px; border: 1px solid #b0bec5; border-radius: 6px; }
    button { padding: 8px 12px; border: 0; border-radius: 6px; background: #00695c; color: #fff; cursor: pointer; }
    ul { list-style: none; padding: 0; margin: 12px 0; }
    li { display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px solid #eceff1; }
    li span { flex: 1; }
    li.done span { text-decoration: line-through; color: #90a4ae; }
    li button { background: transparent; color: #c62828; font-size: 18px; padding: 0 6px; }
    .bar { display: flex; justify-content: space-between; align-items: center; font-size: 14px; color: #607d8b; }
    .filters button { background: #eceff1; color: #263238; padding: 4px 8px; }
    .filters button[aria-pressed="true"] { background: #00695c; color: #fff; }
  </style>
</head>
<body>
  <main class="app">
    <h1>My Tasks</h1>
    <form id="add-form">
      <label for="new" hidden>New task</label>
      <input id="new" placeholder="What needs doing?" autocomplete="off" required maxlength="80">
      <button type="submit">Add</button>
    </form>
    <ul id="list" aria-live="polite"></ul>
    <div class="bar">
      <span id="count"></span>
      <div class="filters">
        <button data-filter="all" aria-pressed="true">All</button>
        <button data-filter="active" aria-pressed="false">Active</button>
        <button data-filter="done" aria-pressed="false">Done</button>
      </div>
    </div>
  </main>
  <script>
    // ---- State ----
    const KEY = "todo-items";
    let filter = "all";
    let todos = load() ?? [
      { id: 1, text: "Finish the CSS Grid lesson", done: true },
      { id: 2, text: "Build the to-do app", done: false },
      { id: 3, text: "Push it to GitHub Pages", done: false },
    ];

    function load() {
      try { return JSON.parse(localStorage.getItem(KEY)); } catch { return null; }
    }
    function save() {
      try { localStorage.setItem(KEY, JSON.stringify(todos)); } catch { /* storage unavailable */ }
    }

    // ---- Rendering ----
    const list = document.getElementById("list");
    function render() {
      const visible = todos.filter(t =>
        filter === "all" ? true : filter === "done" ? t.done : !t.done);
      list.replaceChildren(...visible.map(t => {
        const li = document.createElement("li");
        li.dataset.id = t.id;
        li.classList.toggle("done", t.done);
        const box = document.createElement("input");
        box.type = "checkbox";
        box.checked = t.done;
        box.setAttribute("aria-label", "Mark " + t.text + " as done");
        const span = document.createElement("span");
        span.textContent = t.text;                       // textContent, never innerHTML, for user text
        const del = document.createElement("button");
        del.textContent = "×";
        del.setAttribute("aria-label", "Delete " + t.text);
        del.className = "delete";
        li.append(box, span, del);
        return li;
      }));
      const left = todos.filter(t => !t.done).length;
      document.getElementById("count").textContent = `${left} task${left === 1 ? "" : "s"} left`;
      save();
    }

    // ---- Events ----
    document.getElementById("add-form").addEventListener("submit", e => {
      e.preventDefault();
      const input = document.getElementById("new");
      const text = input.value.trim();
      if (!text) return;
      todos.push({ id: Date.now(), text, done: false });
      input.value = "";
      render();
    });

    list.addEventListener("click", e => {                 // event delegation
      const li = e.target.closest("li");
      if (!li) return;
      const id = Number(li.dataset.id);
      if (e.target.matches("input[type=checkbox]")) {
        const t = todos.find(t => t.id === id);
        t.done = e.target.checked;
      } else if (e.target.matches(".delete")) {
        todos = todos.filter(t => t.id !== id);
      } else return;
      render();
    });

    document.querySelector(".filters").addEventListener("click", e => {
      if (!e.target.dataset.filter) return;
      filter = e.target.dataset.filter;
      document.querySelectorAll(".filters button").forEach(b =>
        b.setAttribute("aria-pressed", b === e.target));
      render();
    });

    render();
  </script>
</body>
</html>

How It Works

  • State. todos is an array of objects with id, text and done. filter remembers which view is selected. The page is never the source of truth; the array is.
  • Loading and saving. load() reads JSON from localStorage; if nothing is stored, ?? [...] supplies three sample tasks. Both functions use try…catch because storage can be disabled, as it is in the preview frame.
  • Rendering. render() filters the tasks, builds an <li> for each with createElement, and swaps them all in with replaceChildren. It also updates the “tasks left” counter and saves. Every change follows the same path: update todos, call render().
  • Safety. Task text is inserted with textContent, never innerHTML, so typing <img onerror=...> shows as harmless text instead of running code.
  • Adding. The form’s submit handler calls preventDefault(), trims the input, ignores empty text, and pushes a new object using Date.now() as a simple unique id.
  • Ticking and deleting. One click listener on the <ul> handles every item, even ones added later. closest("li") finds the item, its data-id finds the task, and matches() tells a checkbox click from a delete click.
  • Filters. The buttons carry data-filter values and aria-pressed, so screen readers know which one is active.

App Structure at a Glance

PartResponsibility
todos, filterThe data (state)
load(), save()Persistence in localStorage
render()Turn state into HTML
Event listenersChange state, then call render()

This one-way flow (events change state, state is rendered) is the same idea that frameworks such as React and Vue are built on, so this project is good preparation for them.

Ideas to Extend the Project

  1. Double-click a task to edit its text.
  2. Add a “Clear completed” button using filter.
  3. Add due dates with <input type="date"> and highlight overdue tasks with the Date object.
  4. Let users reorder tasks by dragging, using the HTML drag-and-drop events.
  5. Publish it alongside your portfolio website.

Common Mistakes

  1. Updating the page and the data separately, so they drift out of sync. Change the data, then render.
  2. Adding a listener to each delete button on every render, creating duplicates. Use delegation on the list.
  3. Using innerHTML with user text, which opens the door to script injection.
  4. Storing objects in localStorage without JSON; they become the useless string “[object Object]”.

Practice Exercises

Exercise 1. Add a “Clear completed” button that removes all done tasks.

Show answer
document.getElementById("clear").addEventListener("click", () => {
  todos = todos.filter(t => !t.done);
  render();
});

Exercise 2. Stop users from adding the same task text twice (ignoring case).

Show answer
const exists = todos.some(t => t.text.toLowerCase() === text.toLowerCase());
if (exists) { alert("That task is already on the list."); return; }

Place this check before todos.push(...) in the submit handler. A message next to the input is friendlier than alert.

Frequently Asked Questions

Why rebuild the whole list on every change?

It keeps the code simple and the page always matches the data. For a few hundred items it is instant. Frameworks optimise this by updating only what changed.

How can I sync tasks between devices?

localStorage stays in one browser. To sync, send the tasks to a server or a service such as Firebase or Supabase using the Fetch API, and load them when the app starts.

Summary

  • Keep state in plain data and render the page from it.
  • Use form submit, event delegation and data- attributes for interaction.
  • Save state as JSON in localStorage, inside try…catch.
  • Insert user text with textContent for safety.

Next: Scope, Hoisting and Closures.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *