Intermediate project: build a to-do app that saves its data
Build a complete to-do app with add, tick, delete, filters and saved data using the DOM, events, delegation and localStorage.
In this lesson you will
- Plan an app around its data
- Write a render function
- Handle events with delegation
- Save and load with localStorage
About 25 minutes
A real app, start to finish
It is time to build something you could genuinely use: a to-do app that lets you add tasks, tick them off, delete them, filter them, and remember everything after you close the browser. It is the classic first app for a reason. It uses almost everything from this module: selecting elements, events, creating elements, delegation, localStorage and JSON. And when it works, you will have built a real application, not just an exercise.
Step 1: plan the data first
Beginners often start with the page. Professionals start with the data. The page is just a picture of the data. Our whole app is one array of objects.
let todos = [
{ id: 1, text: "Learn the DOM", done: true },
{ id: 2, text: "Build a to-do app", done: false }
];
Every feature becomes a small change to this array: adding pushes an object, ticking flips done, deleting filters one out. Then one function, render(), redraws the page from the array. This idea, state in, picture out, is exactly how frameworks like React work, and learning it now will carry you far.
Step 2: the markup and styles
<div class="todo">
<h2>My tasks</h2>
<form id="form">
<input id="input" placeholder="What needs doing?" autocomplete="off">
<button>Add</button>
</form>
<div class="filters">
<button data-filter="all" class="on">All</button>
<button data-filter="open">Open</button>
<button data-filter="done">Done</button>
</div>
<ul id="list"></ul>
<p id="count"></p>
</div>
Step 3: the logic
const KEY = "todos-v1";
let todos = load();
let filter = "all";
function load() {
try { return JSON.parse(localStorage.getItem(KEY)) || []; }
catch (e) { return []; }
}
function save() {
try { localStorage.setItem(KEY, JSON.stringify(todos)); } catch (e) {}
}
function addTodo(text) {
todos.push({ id: Date.now(), text, done: false });
save(); render();
}
function toggleTodo(id) {
const t = todos.find(t => t.id === id);
if (t) t.done = !t.done;
save(); render();
}
function deleteTodo(id) {
todos = todos.filter(t => t.id !== id);
save(); render();
}
See how each function does only three things: change the array, save it, redraw. We use Date.now() as a handy unique id. find locates one task, and filter builds a new array without the deleted one.
Step 4: draw it
function render() {
const visible = todos.filter(t =>
filter === "all" ? true : filter === "done" ? t.done : !t.done);
list.innerHTML = "";
for (const t of visible) {
const li = document.createElement("li");
li.dataset.id = t.id;
li.className = t.done ? "done" : "";
const label = document.createElement("span");
label.textContent = t.text; // safe: no HTML injection
const del = document.createElement("button");
del.textContent = "Delete";
del.className = "delete";
li.append(label, del);
list.append(li);
}
count.textContent = todos.filter(t => !t.done).length + " tasks left";
}
Step 5: the events, using delegation
form.addEventListener("submit", (e) => {
e.preventDefault();
const text = input.value.trim();
if (!text) return;
addTodo(text);
input.value = "";
input.focus();
});
list.addEventListener("click", (e) => {
const li = e.target.closest("li");
if (!li) return;
const id = Number(li.dataset.id);
if (e.target.closest(".delete")) deleteTodo(id);
else toggleTodo(id);
});
document.querySelector(".filters").addEventListener("click", (e) => {
const btn = e.target.closest("button[data-filter]");
if (!btn) return;
filter = btn.dataset.filter;
document.querySelectorAll(".filters button").forEach(b => b.classList.toggle("on", b === btn));
render();
});
render();
Step 6: the finished app
Here is everything together. Add tasks, tick them, delete them and try the filters. The preview uses a small stand-in for storage, so it works inside this sandbox; on your own site it uses real localStorage and your tasks survive a refresh.
Run the app and try it. Then add one improvement: pressing the ‘Clear done’ button should remove all completed tasks. The button is already in the page, so only the logic is missing.
<style>
body{font-family:Arial;background:#F4F1FC;padding:14px;color:#14112E}
.todo{max-width:380px;margin:auto;background:#fff;padding:18px;border-radius:16px;box-shadow:0 8px 24px rgba(20,17,46,.1)}
h2{margin:0 0 10px;color:#5A28C8}
form{display:flex;gap:6px}
input{flex:1;padding:10px;font-size:15px;border:1px solid #D9D3EE;border-radius:8px;min-width:0}
button{cursor:pointer;border:0;border-radius:8px;font-weight:700}
form button{background:#5A28C8;color:#fff;padding:0 14px}
.filters{display:flex;gap:6px;margin:12px 0}
.filters button{background:#EFEAFD;color:#5A28C8;padding:6px 12px}
.filters button.on{background:#5A28C8;color:#fff}
ul{list-style:none;padding:0;margin:0}
li{display:flex;justify-content:space-between;align-items:center;gap:8px;padding:10px;border-bottom:1px solid #EFEAFD;cursor:pointer}
li.done span{text-decoration:line-through;color:#9A95BC}
.delete{background:#F06CC2;color:#fff;padding:4px 10px}
#count{color:#5F5B80;font-size:14px}
#clear{background:none;color:#5A28C8;text-decoration:underline;padding:0}
</style>
<div class="todo">
<h2>My tasks</h2>
<form id="form"><input id="input" placeholder="What needs doing?" autocomplete="off"><button>Add</button></form>
<div class="filters">
<button data-filter="all" class="on">All</button><button data-filter="open">Open</button><button data-filter="done">Done</button>
</div>
<ul id="list"></ul>
<p id="count"></p>
<button id="clear">Clear done</button>
</div>
<script>
let store;
try { localStorage.setItem('t','1'); localStorage.removeItem('t'); store = localStorage; }
catch (e) { const m = {}; store = { getItem: k => (k in m ? m[k] : null), setItem: (k, v) => { m[k] = String(v); } }; }
const KEY = 'todos-v1';
const list = document.getElementById('list');
const count = document.getElementById('count');
const form = document.getElementById('form');
const input = document.getElementById('input');
let filter = 'all';
let todos = (function () { try { return JSON.parse(store.getItem(KEY)) || []; } catch (e) { return []; } })();
if (!todos.length) todos = [{ id: 1, text: 'Learn the DOM', done: true }, { id: 2, text: 'Build a to-do app', done: false }];
function save() { store.setItem(KEY, JSON.stringify(todos)); }
function render() {
const visible = todos.filter(t => filter === 'all' ? true : filter === 'done' ? t.done : !t.done);
list.innerHTML = '';
for (const t of visible) {
const li = document.createElement('li');
li.dataset.id = t.id;
if (t.done) li.className = 'done';
const label = document.createElement('span'); label.textContent = t.text;
const del = document.createElement('button'); del.textContent = 'Delete'; del.className = 'delete';
li.append(label, del); list.append(li);
}
count.textContent = todos.filter(t => !t.done).length + ' tasks left';
}
form.addEventListener('submit', function (e) {
e.preventDefault();
const text = input.value.trim();
if (!text) return;
todos.push({ id: Date.now(), text: text, done: false });
save(); render(); input.value = ''; input.focus();
});
list.addEventListener('click', function (e) {
const li = e.target.closest('li'); if (!li) return;
const id = Number(li.dataset.id);
if (e.target.closest('.delete')) todos = todos.filter(t => t.id !== id);
else { const t = todos.find(t => t.id === id); if (t) t.done = !t.done; }
save(); render();
});
document.querySelector('.filters').addEventListener('click', function (e) {
const b = e.target.closest('button[data-filter]'); if (!b) return;
filter = b.dataset.filter;
document.querySelectorAll('.filters button').forEach(x => x.classList.toggle('on', x === b));
render();
});
// TODO: make #clear remove all done tasks
render();
</script>
document.getElementById(‘clear’).addEventListener(‘click’, () => { todos = todos.filter(t => !t.done); save(); render(); });
<style>
body{font-family:Arial;background:#F4F1FC;padding:14px;color:#14112E}
.todo{max-width:380px;margin:auto;background:#fff;padding:18px;border-radius:16px;box-shadow:0 8px 24px rgba(20,17,46,.1)}
h2{margin:0 0 10px;color:#5A28C8}
form{display:flex;gap:6px}
input{flex:1;padding:10px;font-size:15px;border:1px solid #D9D3EE;border-radius:8px;min-width:0}
button{cursor:pointer;border:0;border-radius:8px;font-weight:700}
form button{background:#5A28C8;color:#fff;padding:0 14px}
.filters{display:flex;gap:6px;margin:12px 0}
.filters button{background:#EFEAFD;color:#5A28C8;padding:6px 12px}
.filters button.on{background:#5A28C8;color:#fff}
ul{list-style:none;padding:0;margin:0}
li{display:flex;justify-content:space-between;align-items:center;gap:8px;padding:10px;border-bottom:1px solid #EFEAFD;cursor:pointer}
li.done span{text-decoration:line-through;color:#9A95BC}
.delete{background:#F06CC2;color:#fff;padding:4px 10px}
#count{color:#5F5B80;font-size:14px}
#clear{background:none;color:#5A28C8;text-decoration:underline;padding:0}
</style>
<div class="todo">
<h2>My tasks</h2>
<form id="form"><input id="input" placeholder="What needs doing?" autocomplete="off"><button>Add</button></form>
<div class="filters">
<button data-filter="all" class="on">All</button><button data-filter="open">Open</button><button data-filter="done">Done</button>
</div>
<ul id="list"></ul>
<p id="count"></p>
<button id="clear">Clear done</button>
</div>
<script>
let store;
try { localStorage.setItem('t','1'); localStorage.removeItem('t'); store = localStorage; }
catch (e) { const m = {}; store = { getItem: k => (k in m ? m[k] : null), setItem: (k, v) => { m[k] = String(v); } }; }
const KEY = 'todos-v1';
const list = document.getElementById('list');
const count = document.getElementById('count');
const form = document.getElementById('form');
const input = document.getElementById('input');
let filter = 'all';
let todos = (function () { try { return JSON.parse(store.getItem(KEY)) || []; } catch (e) { return []; } })();
if (!todos.length) todos = [{ id: 1, text: 'Learn the DOM', done: true }, { id: 2, text: 'Build a to-do app', done: false }];
function save() { store.setItem(KEY, JSON.stringify(todos)); }
function render() {
const visible = todos.filter(t => filter === 'all' ? true : filter === 'done' ? t.done : !t.done);
list.innerHTML = '';
for (const t of visible) {
const li = document.createElement('li');
li.dataset.id = t.id;
if (t.done) li.className = 'done';
const label = document.createElement('span'); label.textContent = t.text;
const del = document.createElement('button'); del.textContent = 'Delete'; del.className = 'delete';
li.append(label, del); list.append(li);
}
count.textContent = todos.filter(t => !t.done).length + ' tasks left';
}
form.addEventListener('submit', function (e) {
e.preventDefault();
const text = input.value.trim();
if (!text) return;
todos.push({ id: Date.now(), text: text, done: false });
save(); render(); input.value = ''; input.focus();
});
list.addEventListener('click', function (e) {
const li = e.target.closest('li'); if (!li) return;
const id = Number(li.dataset.id);
if (e.target.closest('.delete')) todos = todos.filter(t => t.id !== id);
else { const t = todos.find(t => t.id === id); if (t) t.done = !t.done; }
save(); render();
});
document.querySelector('.filters').addEventListener('click', function (e) {
const b = e.target.closest('button[data-filter]'); if (!b) return;
filter = b.dataset.filter;
document.querySelectorAll('.filters button').forEach(x => x.classList.toggle('on', x === b));
render();
});
document.getElementById('clear').addEventListener('click', function () {
todos = todos.filter(t => !t.done);
save(); render();
});
render();
</script>
Why this design works
- One source of truth. The array is the only place the truth lives. The page is rebuilt from it, so the two can never disagree.
- Small functions. Add, toggle, delete and render are each a few lines and easy to test in the console.
- Safe by default. Text goes in with
textContent, so a task named<script>is displayed, not executed. - Fast enough. Redrawing a list of a few hundred items is instant. If you ever reach thousands, you would redraw only what changed.
Ideas to take it further
- Double-click a task to edit its text.
- Add due dates and sort by them.
- Add categories with colour labels.
- Drag to reorder with the pointer events.
- Add an “undo delete” toast that lasts five seconds, using a timer.
- Load starter tasks from an API with fetch.
Mixing up the page and the data: reading a task’s state from the page (checking a CSS class) instead of from the array. Always change the array first, then redraw. Then your saved data and your screen stay in step.
If you built this app and understand why it works, you have the mindset needed for frameworks, for larger JavaScript projects, and for the advanced lessons that follow: closures, classes, modules and error handling.
Practice: add a task counter message
A good habit is to improve a working app in small steps. Here is a tiny change: when no tasks exist at all, show a friendly empty message instead of a blank list. It takes four lines and makes the app feel finished.
Run this mini list. Fill in the empty-state check so the paragraph shows ‘Nothing to do. Enjoy your day!’ when the array is empty, and the count otherwise. Then add a task with push and call render again.
<style>body{font-family:Arial;padding:14px} li{margin:4px 0} #msg{color:#5F5B80}</style>
<ul id="list"></ul>
<p id="msg"></p>
<button id="fill">Add a task</button>
<script>
const list = document.getElementById('list');
const msg = document.getElementById('msg');
let todos = [];
function render() {
list.innerHTML = todos.map(t => '<li>' + t + '</li>').join('');
// empty-state message here
}
document.getElementById('fill').addEventListener('click', function () {
todos.push('Task ' + (todos.length + 1));
render();
});
render();
</script>
msg.textContent = todos.length === 0 ? ‘Nothing to do. Enjoy your day!’ : todos.length + ‘ tasks’;
<style>body{font-family:Arial;padding:14px} li{margin:4px 0} #msg{color:#5F5B80}</style>
<ul id="list"></ul>
<p id="msg"></p>
<button id="fill">Add a task</button>
<script>
const list = document.getElementById('list');
const msg = document.getElementById('msg');
let todos = [];
function render() {
list.innerHTML = todos.map(t => '<li>' + t + '</li>').join('');
msg.textContent = todos.length === 0 ? 'Nothing to do. Enjoy your day!' : todos.length + ' tasks';
}
document.getElementById('fill').addEventListener('click', function () {
todos.push('Task ' + (todos.length + 1));
render();
});
render();
</script>
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why plan the data before the page?
- The page is just a picture of the data
- Data is prettier
- It’s required by HTML
- It makes CSS faster
Every feature becomes a change to the data.
What does render() do in the to-do app?
- Saves to a server
- Redraws the list from the todos array
- Deletes tasks
- Adds CSS
State in, picture out.
Which method locates one task by id?
todos.map(...)todos.join(...)todos.reverse()todos.find(...)
find returns the first match.
How is a task deleted?
todos.delete(id)todos = todos.filter(t => t.id !== id)li.hide()todos.length = 0
filter builds a new array without it.
Why use event delegation on the list?
- It is required by localStorage
- It makes tasks bold
- Lists cannot have listeners
- New items work without new listeners
One parent listener handles all items.
Summary
- Keep the state in one array of objects.
- Change the data, save, then render.
- Use delegation for lists.
- textContent keeps user text safe.
Questions
My tasks disappear on refresh. Why?
Check that save() runs after each change and that load() parses the saved JSON on start. Private windows also clear storage.
How do I edit a task?
Replace the text span with an input on double click, then update the object and call render.
Could I turn this into a React app?
Yes. React formalises exactly this idea of state in, page out, so this project is a great stepping stone.
