Project: To-Do List App
Time to put the series together. In this project you will build a complete to-do list app that lets you add tasks, tick them off, delete them, filter them and keep them after a reload. It uses DOM selection, creating elements, events and delegation, form handling, JSON and localStorage: the everyday toolkit of front-end JavaScript.
The goal
By the end you will have a single HTML file that can:
- Add a task by typing and pressing Enter or clicking Add (empty tasks are ignored);
- Complete a task by ticking its checkbox, which crosses it out;
- Delete a task, or clear all completed tasks at once;
- Filter the list to All, Active or Done, with a live "items left" counter;
- Save everything to localStorage so it survives a reload.
The plan: state, render, events, save
Beginners often change the page directly in every event handler: add an li here, remove one there, tweak the counter somewhere else. That quickly gets out of sync. Professional apps follow a simpler idea:
- Keep the data in one place, the state: an array of task objects plus the current filter.
- Write one
render()function that rebuilds the list from the state. - Event handlers only update the state, then call
saveTodos()andrender(). - On start-up, load the state from localStorage and render once.
render() → page → events → state. Every change is saved, and the saved copy is loaded once at start-up (dashed).Each task is a small object, for example { id: 1763190000000, text: "Buy unga", done: false }. The id lets us find the right task when its row is clicked; Date.now(), the number of milliseconds since 1970, is unique enough for tasks typed by hand.
Step 1: the HTML
A form for new tasks, an empty list that JavaScript will fill, and a footer with the counter, filter buttons and a clear button. The data-filter attributes tell our code which filter each button means.
<h1>My to-do list</h1>
<form id="todo-form">
<input id="new-todo" placeholder="What needs doing?" autocomplete="off">
<button>Add</button>
</form>
<ul id="todo-list"></ul>
<p id="empty">Nothing to show.</p>
<footer>
<span id="counter"></span>
<div class="filters">
<button type="button" data-filter="all">All</button>
<button type="button" data-filter="active">Active</button>
<button type="button" data-filter="done">Done</button>
</div>
<button type="button" id="clear-done">Clear done</button>
</footer>
Step 2: state, loading and saving
Select the elements once, then set up the state. Loading uses the pattern from Local Storage: parse the saved JSON, fall back to an empty array, and catch errors in case storage is blocked or the saved text is corrupt.
const STORAGE_KEY = "kuza-todos";
const form = document.querySelector("#todo-form");
const input = document.querySelector("#new-todo");
const list = document.querySelector("#todo-list");
const empty = document.querySelector("#empty");
const counter = document.querySelector("#counter");
const filtersBox = document.querySelector(".filters");
const filterButtons = document.querySelectorAll(".filters button");
const clearDone = document.querySelector("#clear-done");
let todos = loadTodos();
let filter = "all";
function loadTodos() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? [];
} catch {
return []; // storage blocked or data corrupt: start fresh
}
}
function saveTodos() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
} catch {
// storage unavailable: the app still works, it just won't remember
}
}
Calling loadTodos() before its definition is fine, because function declarations are hoisted.
Step 3: render the state
render() works out which tasks are visible under the current filter, empties the list, and builds one li per task with createElement. Using textContent for the task text means a task like <b>hi</b> is shown as text, never run as HTML.
function render() {
const visible = todos.filter((todo) => {
if (filter === "active") return !todo.done;
if (filter === "done") return todo.done;
return true;
});
list.replaceChildren(); // remove the old rows
for (const todo of visible) {
const li = document.createElement("li");
li.dataset.id = todo.id;
li.classList.toggle("done", todo.done);
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "toggle";
checkbox.checked = todo.done;
const text = document.createElement("span");
text.textContent = todo.text;
const del = document.createElement("button");
del.className = "delete";
del.textContent = "Delete";
del.setAttribute("aria-label", `Delete ${todo.text}`);
li.append(checkbox, text, del);
list.append(li);
}
empty.hidden = visible.length > 0;
const left = todos.filter((todo) => !todo.done).length;
counter.textContent = `${left} item${left === 1 ? "" : "s"} left`;
filterButtons.forEach((btn) => {
btn.classList.toggle("active", btn.dataset.filter === filter);
});
}
Step 4: add tasks with the form
Listen for submit so both Enter and the Add button work, and call preventDefault() to stop the reload (see Handling Forms).
form.addEventListener("submit", (event) => {
event.preventDefault();
const text = input.value.trim();
if (text === "") return; // ignore empty tasks
todos.push({ id: Date.now(), text, done: false });
input.value = "";
saveTodos();
render();
});
Step 5: complete and delete with one delegated listener
The rows are rebuilt on every render, so attaching listeners to each checkbox would be wasteful. One listener on the ul handles every row, past and future (event delegation). Remember that dataset values are strings, so convert the id back to a number.
list.addEventListener("click", (event) => {
const li = event.target.closest("li");
if (!li) return;
const id = Number(li.dataset.id);
if (event.target.matches(".delete")) {
todos = todos.filter((todo) => todo.id !== id);
} else if (event.target.matches(".toggle")) {
const todo = todos.find((todo) => todo.id === id);
todo.done = !todo.done;
} else {
return; // clicked the text: nothing to do
}
saveTodos();
render();
});
Step 6: filters and clearing
filtersBox.addEventListener("click", (event) => {
const btn = event.target.closest("button[data-filter]");
if (!btn) return;
filter = btn.dataset.filter;
render(); // the filter is a view choice, so no need to save
});
clearDone.addEventListener("click", () => {
todos = todos.filter((todo) => !todo.done);
saveTodos();
render();
});
render(); // draw the saved tasks on start-up
Changing the state but forgetting to call render() (the page doesn't update) or saveTodos() (the change vanishes on reload). Keeping "update state, save, render" together at the end of every handler avoids both bugs.
The complete app
Here is everything in one file, with some CSS. Click Try it yourself to use it. The preview on this site blocks storage, so tasks won't survive pressing Run; save the code as todo.html and open it in your browser to see saving work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>To-do list</title>
<style>
body { font-family: sans-serif; max-width: 440px; margin: 20px auto; padding: 0 12px; }
form { display: flex; gap: 6px; }
#new-todo { flex: 1; padding: 6px; }
ul { list-style: none; padding: 0; }
li { display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px solid #ddd; }
li span { flex: 1; }
li.done span { text-decoration: line-through; color: #888; }
#empty { color: #888; }
footer { display: flex; flex-wrap: wrap; gap: 8px; justify-content: space-between; align-items: center; }
.filters button.active { background: #1f2d42; color: white; }
</style>
</head>
<body>
<h1>My to-do list</h1>
<form id="todo-form">
<input id="new-todo" placeholder="What needs doing?" autocomplete="off">
<button>Add</button>
</form>
<ul id="todo-list"></ul>
<p id="empty">Nothing to show.</p>
<footer>
<span id="counter"></span>
<div class="filters">
<button type="button" data-filter="all">All</button>
<button type="button" data-filter="active">Active</button>
<button type="button" data-filter="done">Done</button>
</div>
<button type="button" id="clear-done">Clear done</button>
</footer>
<script>
const STORAGE_KEY = "kuza-todos";
const form = document.querySelector("#todo-form");
const input = document.querySelector("#new-todo");
const list = document.querySelector("#todo-list");
const empty = document.querySelector("#empty");
const counter = document.querySelector("#counter");
const filtersBox = document.querySelector(".filters");
const filterButtons = document.querySelectorAll(".filters button");
const clearDone = document.querySelector("#clear-done");
let todos = loadTodos();
let filter = "all";
function loadTodos() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? [];
} catch {
return [];
}
}
function saveTodos() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
} catch {
// storage unavailable: keep working without saving
}
}
function render() {
const visible = todos.filter((todo) => {
if (filter === "active") return !todo.done;
if (filter === "done") return todo.done;
return true;
});
list.replaceChildren();
for (const todo of visible) {
const li = document.createElement("li");
li.dataset.id = todo.id;
li.classList.toggle("done", todo.done);
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "toggle";
checkbox.checked = todo.done;
const text = document.createElement("span");
text.textContent = todo.text;
const del = document.createElement("button");
del.className = "delete";
del.textContent = "Delete";
del.setAttribute("aria-label", `Delete ${todo.text}`);
li.append(checkbox, text, del);
list.append(li);
}
empty.hidden = visible.length > 0;
const left = todos.filter((todo) => !todo.done).length;
counter.textContent = `${left} item${left === 1 ? "" : "s"} left`;
filterButtons.forEach((btn) => {
btn.classList.toggle("active", btn.dataset.filter === filter);
});
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const text = input.value.trim();
if (text === "") return;
todos.push({ id: Date.now(), text, done: false });
input.value = "";
saveTodos();
render();
});
list.addEventListener("click", (event) => {
const li = event.target.closest("li");
if (!li) return;
const id = Number(li.dataset.id);
if (event.target.matches(".delete")) {
todos = todos.filter((todo) => todo.id !== id);
} else if (event.target.matches(".toggle")) {
const todo = todos.find((todo) => todo.id === id);
todo.done = !todo.done;
} else {
return;
}
saveTodos();
render();
});
filtersBox.addEventListener("click", (event) => {
const btn = event.target.closest("button[data-filter]");
if (!btn) return;
filter = btn.dataset.filter;
render();
});
clearDone.addEventListener("click", () => {
todos = todos.filter((todo) => !todo.done);
saveTodos();
render();
});
render();
</script>
</body>
</html>
Sample run
Add "Buy unga", "Revise JavaScript" and "Call mum", tick "Call mum", then click Active. The page shows the two unfinished tasks, and DevTools (Application → Local Storage) shows the saved JSON. Your ids will be different, because they come from the clock.
Reload the page (in your own browser) and all three tasks come back, with "Call mum" still ticked.
Extend it
- Edit tasks. On a double-click of a task's text, swap the
spanfor aninput; save the new text on Enter or when the input loses focus (blur), and cancel on Escape. - Due dates and priorities. Add a date input and a priority select to the form, store them on each task object, sort the visible tasks by date, and highlight overdue tasks with a class.
- Sync with an API. Load starter tasks with
fetch("https://jsonplaceholder.typicode.com/todos?_limit=5"), mapping each item'stitleandcompletedinto your own task shape, and show a loading message and an error message using async/await withtry/catch.
Key points
- Keep data in one state array and rebuild the page from it with a single
render()function. - Event handlers update state, then save and render; a form
submithandler withpreventDefault()adds tasks. - One delegated listener on the list handles toggles and deletes for every row, including new ones.
- Save with
JSON.stringify, load withJSON.parseand a fallback, and wrap storage intry/catch.
Tip: use the ← and → keys to move between pages.
