Project: To-Do List
A to-do list is the classic JavaScript project because it uses almost everything a real app needs: a form, a list rendered from data, several kinds of changes, filtering, derived counts and persistence. This one is the Fee Tracker office's task list ("Email Navika's receipt", "Call about the late fee"). It follows the same state, render, dispatch loop as the counter, adds a reducer for its actions, and handles every click in the list with one delegated listener.
What You'll Build
- A form to add a task (Enter or the Add button), rejecting empty tasks.
- Each task can be completed (checkbox), renamed (double-click, then Enter or Escape) and deleted.
- Filters: All, Active, Completed, kept in the URL hash so a filtered view can be bookmarked.
- A live count of remaining tasks and a "Clear completed" button.
- Everything saved in
localStorage.
Step 1: The HTML
<section class="todo" aria-labelledby="todo-title">
<h2 id="todo-title">Office tasks</h2>
<form id="new-task">
<label for="task-text">New task</label>
<input id="task-text" name="text" autocomplete="off" required maxlength="120">
<button>Add</button>
</form>
<ul id="tasks" aria-live="polite"></ul>
<footer>
<span id="remaining"></span>
<nav aria-label="Filter tasks">
<a href="#/all">All</a> <a href="#/active">Active</a> <a href="#/completed">Completed</a>
</nav>
<button type="button" id="clear">Clear completed</button>
</footer>
</section>The form uses a real <form> and required, so pressing Enter submits and empty input is caught by the browser. Filters are links, so they work with Back and Forward and can be bookmarked.
Step 2: State and the Reducer
State holds the tasks and the current filter. Every change is an action handled by one pure reducer:
function reducer(state, action) {
switch (action.type) {
case "added": {
const text = action.text.trim();
if (!text) return state;
const id = Math.max(0, ...state.tasks.map((t) => t.id)) + 1;
return { ...state, tasks: [...state.tasks, { id, text, done: false }] };
}
case "toggled":
return { ...state, tasks: state.tasks.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t)) };
case "renamed": {
const text = action.text.trim();
if (!text) return reducer(state, { type: "deleted", id: action.id });
return { ...state, tasks: state.tasks.map((t) => (t.id === action.id ? { ...t, text } : t)) };
}
case "deleted":
return { ...state, tasks: state.tasks.filter((t) => t.id !== action.id) };
case "cleared":
return { ...state, tasks: state.tasks.filter((t) => !t.done) };
case "filtered":
return { ...state, filter: ["all", "active", "completed"].includes(action.filter) ? action.filter : "all" };
default:
return state;
}
}
let state = { tasks: [], filter: "all" };
for (const action of [
{ type: "added", text: "Email Navika's receipt" },
{ type: "added", text: " " },
{ type: "added", text: "Call about Advitha's late fee" },
{ type: "toggled", id: 1 },
{ type: "renamed", id: 2, text: "Call Srihitha about the late fee" },
{ type: "filtered", filter: "active" },
]) state = reducer(state, action);
console.log(state);{ tasks: [{ id: 1, text: 'Email Navika's receipt', done: true }, { id: 2, text: 'Call Srihitha about the late fee', done: false }], filter: 'active' }The blank task was ignored, and renaming a task to an empty string deletes it, a common to-do list convention. Because the reducer is pure, every rule here can be tested without a browser.
Step 3: Derived Values
The visible list and the remaining count are derived from state, never stored:
const visibleTasks = ({ tasks, filter }) =>
filter === "active" ? tasks.filter((t) => !t.done) : filter === "completed" ? tasks.filter((t) => t.done) : tasks;
const remainingLabel = ({ tasks }) => {
const n = tasks.filter((t) => !t.done).length;
return `${n} ${n === 1 ? "task" : "tasks"} left`;
};
const state = { filter: "completed", tasks: [{ id: 1, text: "A", done: true }, { id: 2, text: "B", done: false }] };
console.log(visibleTasks(state).map((t) => t.text), remainingLabel(state));['A'] 1 task leftStep 4: Rendering
render rebuilds the list from state with createElement and textContent, so a task named <b>urgent</b> shows exactly that text. Each item carries its ID in a data- attribute for the delegated listener:
function renderTask(task) {
const li = document.createElement("li");
li.dataset.id = task.id;
li.classList.toggle("done", task.done);
const box = Object.assign(document.createElement("input"), { type: "checkbox", checked: task.done });
box.setAttribute("aria-label", `Mark "${task.text}" as done`);
const label = Object.assign(document.createElement("span"), { textContent: task.text });
const del = Object.assign(document.createElement("button"), { type: "button", textContent: "Delete" });
del.dataset.action = "delete";
del.setAttribute("aria-label", `Delete "${task.text}"`);
li.append(box, label, del);
return li;
}Step 5: One Delegated Listener
Instead of a listener per task (which would need adding and removing as tasks change), one listener on the list handles everything, using closest to find which task was used:
list.addEventListener("click", (event) => {
const li = event.target.closest("li[data-id]");
if (!li) return;
const id = Number(li.dataset.id);
if (event.target.matches('input[type="checkbox"]')) dispatch({ type: "toggled", id });
if (event.target.closest('[data-action="delete"]')) dispatch({ type: "deleted", id });
});Step 6: Editing in Place
Double-clicking a task's text swaps it for an input; Enter saves, Escape cancels, and leaving the field saves:
list.addEventListener("dblclick", (event) => {
const span = event.target.closest("li[data-id] span");
if (!span) return;
const id = Number(span.closest("li").dataset.id);
const input = Object.assign(document.createElement("input"), { value: span.textContent });
span.replaceWith(input);
input.focus();
let done = false;
const finish = (save) => {
if (done) return;
done = true;
save ? dispatch({ type: "renamed", id, text: input.value }) : render(state);
};
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") finish(true);
if (e.key === "Escape") finish(false);
});
input.addEventListener("blur", () => finish(true));
});The done flag prevents saving twice (Enter re-renders the list, which removes the input and would also trigger blur).
The Complete App
Everything wired together. The checker adds three tasks, completes the first, filters to active ones, then clears completed tasks:
<form id="new-task"><label for="task-text">New task</label> <input id="task-text" required> <button id="add">Add</button></form>
<ul id="tasks"></ul>
<p><span id="remaining"></span> <a href="#/all">All</a> <a href="#/active">Active</a> <a href="#/completed">Completed</a>
<button type="button" id="clear">Clear completed</button></p>
<script type="module">
const KEY = "feeTracker.todos";
function reducer(state, a) {
switch (a.type) {
case "added": { const text = a.text.trim(); if (!text) return state; const id = Math.max(0, ...state.tasks.map((t) => t.id)) + 1; return { ...state, tasks: [...state.tasks, { id, text, done: false }] }; }
case "toggled": return { ...state, tasks: state.tasks.map((t) => (t.id === a.id ? { ...t, done: !t.done } : t)) };
case "deleted": return { ...state, tasks: state.tasks.filter((t) => t.id !== a.id) };
case "cleared": return { ...state, tasks: state.tasks.filter((t) => !t.done) };
case "filtered": return { ...state, filter: ["all", "active", "completed"].includes(a.filter) ? a.filter : "all" };
default: return state;
}
}
const visible = ({ tasks, filter }) => (filter === "active" ? tasks.filter((t) => !t.done) : filter === "completed" ? tasks.filter((t) => t.done) : tasks);
const load = () => { try { const t = JSON.parse(localStorage.getItem(KEY) ?? "[]"); return Array.isArray(t) ? t : []; } catch { return []; } };
let state = { tasks: load(), filter: location.hash.slice(2) || "all" };
const list = document.querySelector("#tasks");
function render(s) {
list.replaceChildren(...visible(s).map((t) => {
const li = document.createElement("li");
li.dataset.id = t.id;
const box = Object.assign(document.createElement("input"), { type: "checkbox", checked: t.done });
const label = Object.assign(document.createElement("span"), { textContent: t.text });
const del = Object.assign(document.createElement("button"), { type: "button", textContent: "Delete" });
del.dataset.action = "delete";
li.append(box, label, del);
return li;
}));
const left = s.tasks.filter((t) => !t.done).length;
document.querySelector("#remaining").textContent = `${left} ${left === 1 ? "task" : "tasks"} left`;
console.log(`[${s.filter}] ${visible(s).map((t) => (t.done ? "x " : "o ") + t.text).join(" | ") || "(none)"} | ${document.querySelector("#remaining").textContent}`);
}
function dispatch(action) {
state = reducer(state, action);
localStorage.setItem(KEY, JSON.stringify(state.tasks));
render(state);
}
document.querySelector("#new-task").addEventListener("submit", (e) => {
e.preventDefault();
const input = document.querySelector("#task-text");
dispatch({ type: "added", text: input.value });
input.value = "";
});
list.addEventListener("click", (e) => {
const li = e.target.closest("li[data-id]");
if (!li) return;
const id = Number(li.dataset.id);
if (e.target.matches('input[type="checkbox"]')) dispatch({ type: "toggled", id });
if (e.target.closest('[data-action="delete"]')) dispatch({ type: "deleted", id });
});
document.querySelector("#clear").addEventListener("click", () => dispatch({ type: "cleared" }));
window.addEventListener("hashchange", () => dispatch({ type: "filtered", filter: location.hash.slice(2) }));
render(state);
</script>[all] (none) | 0 tasks left
[all] o Email Navika's receipt | 1 task left
[all] o Email Navika's receipt | o Call Srihitha | 2 tasks left
[all] o Email Navika's receipt | o Call Srihitha | o <b>Update</b> Advitha's fees | 3 tasks left
[all] x Email Navika's receipt | o Call Srihitha | o <b>Update</b> Advitha's fees | 2 tasks left
[active] o Call Srihitha | o <b>Update</b> Advitha's fees | 2 tasks left
[active] o Call Srihitha | o <b>Update</b> Advitha's fees | 2 tasks left
[all] o Call Srihitha | o <b>Update</b> Advitha's fees | 2 tasks leftThe task containing <b> is displayed as text, not bold, because every task is inserted with textContent. Clearing completed tasks removed the first one (the active view looked the same before and after, since it already hid completed tasks).
Practice
Challenge: Add a "toggled-all" action that marks every task done, or, if all are already done, marks them all active. Write it as a reducer case and test it:
Show solution
function toggleAll(state) {
const allDone = state.tasks.length > 0 && state.tasks.every((t) => t.done);
return { ...state, tasks: state.tasks.map((t) => ({ ...t, done: !allDone })) };
}
let state = { tasks: [{ id: 1, done: false }, { id: 2, done: true }] };
state = toggleAll(state);
console.log(state.tasks.map((t) => t.done));
state = toggleAll(state);
console.log(state.tasks.map((t) => t.done));[true, true]
[false, false]Key Takeaways
| Feature | Technique |
|---|---|
| Adding | submit event, added action |
| Completing, deleting | Delegated click, data-id |
| Editing | dblclick, swap in an input, Enter/Escape |
| Filtering | URL hash, hashchange, selector |
| Saving | localStorage with JSON and validation |
Was this tutorial helpful?