Project: Todo App
Put everything you've learned together by building a complete, real-world Todo App using pure vanilla JavaScript — no frameworks, no libraries. Add tasks, mark them done, filter by status, edit inline, and persist data with localStorage.
localStorageProject Overview
The Todo App is the classic first JavaScript project — simple enough to build in one session, rich enough to touch all the core concepts: state management, DOM rendering, events, data persistence, and UI feedback. By the end of this chapter you'll have a fully working app you can deploy.
localStorage automatically.Concepts Used in This Project
This project is a practical recap of what you've learned across the course. Here are the key concepts applied:
Project File Structure
Keep the project simple — three files. All the JavaScript lives in app.js. The HTML provides structure; CSS handles styling. No
build tools needed.
Step-by-Step Build Plan
We'll build the app in six clear steps. Each step produces working, runnable code before we move to the next:
id or
data-* attribute for easy JS selection.
state object with a
todos array and filter string. Write loadState() and saveState() to sync with localStorage.
render()
function that re-draws the entire list from state every time data changes. Use innerHTML with a template literal loop.{ id, text, completed }. Use event
delegation on the list container for delete buttons.completed on checkbox
click. Wire up filter buttons to update state.filter
and re-render the correct subset of todos.Step 1 — HTML Skeleton
Start with clean semantic HTML. Every interactive element gets a data-action attribute so the JavaScript can identify what was
clicked without needing brittle class name checks:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Todo App — Vanilla JS</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="todo-wrapper">
<!-- Header -->
<h1 class="todo-heading">
<span>✅</span> My Todos
</h1>
<!-- Input row -->
<div class="todo-input-row">
<input
id="todoInput"
type="text"
placeholder="What needs to be done?"
autocomplete="off"
/>
<button id="addBtn">Add</button>
</div>
<!-- Filter tabs -->
<div class="todo-filters" id="filterBar">
<button data-filter="all" class="filter-btn active">All</button>
<button data-filter="active" class="filter-btn">Active</button>
<button data-filter="completed" class="filter-btn">Completed</button>
</div>
<!-- Todo list -->
<ul class="todo-list" id="todoList"></ul>
<!-- Footer -->
<div class="todo-footer" id="todoFooter">
<span id="itemCount">0 items left</span>
<button id="clearCompleted">Clear Completed</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
Step 2 — State & localStorage
The entire app's data lives in one state
object. This makes it trivial to save and restore data — we just JSON.stringify() the state on every change and JSON.parse() it on load:
// ─── State ────────────────────────────────────────────────────
const STORAGE_KEY = 'k2_todos';
let state = {
todos: [], // array of { id, text, completed }
filter: 'all' // 'all' | 'active' | 'completed'
};
// ─── Persistence ──────────────────────────────────────────────
function loadState() {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) state.todos = JSON.parse(saved);
} catch (e) {
state.todos = []; // corrupt data → start fresh
}
}
function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state.todos));
}
// ─── Unique ID helper ─────────────────────────────────────────
function uid() {
return Date.now().toString(36) + Math.random().toString(36).slice(2);
}
Step 3 — Render Function
A single render() function reads state
and repaints the UI. We filter the todos array, map each item to an HTML string, then set innerHTML once. This avoids scattered DOM mutations and is
easy to reason about:
function getFiltered() {
if (state.filter === 'active') return state.todos.filter(t => !t.completed);
if (state.filter === 'completed') return state.todos.filter(t => t.completed);
return state.todos;
}
function render() {
const list = document.getElementById('todoList');
const countEl = document.getElementById('itemCount');
const filtered = getFiltered();
const active = state.todos.filter(t => !t.completed).length;
// Update item count
countEl.textContent = `${active} item${active !== 1 ? 's' : ''} left`;
// Render list items
list.innerHTML = filtered.length
? filtered.map(t => `
<li class="todo-item${t.completed ? ' done' : ''}" data-id="${t.id}">
<input type="checkbox" ${t.completed ? 'checked' : ''} data-action="toggle" />
<span class="todo-text" data-action="edit">${escHtml(t.text)}</span>
<button class="todo-del" data-action="delete">✕</button>
</li>`).join('')
: '<li class="todo-empty">Nothing here yet ✨</li>';
// Sync filter buttons
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.filter === state.filter);
});
}
// Prevent XSS — escape user-supplied text
function escHtml(str) {
const d = document.createElement('div');
d.textContent = str;
return d.innerHTML;
}
<img src=x onerror=alert(1)> as a
task, we must not inject that raw into innerHTML. The escHtml()
helper converts dangerous characters to safe HTML entities automatically.
Step 4 — Add & Delete
Mutate the state.todos array, call saveState(), then call render(). That three-step pattern is used for every
action in the app:
// ─── Add Task ─────────────────────────────────────────────────
function addTodo(text) {
text = text.trim();
if (!text) {
document.getElementById('todoInput').classList.add('shake');
setTimeout(() => document.getElementById('todoInput').classList.remove('shake'), 500);
return;
}
state.todos.push({ id: uid(), text, completed: false });
saveState();
render();
document.getElementById('todoInput').value = '';
}
// ─── Delete Task ──────────────────────────────────────────────
function deleteTodo(id) {
state.todos = state.todos.filter(t => t.id !== id);
saveState();
render();
}
// ─── Clear Completed ──────────────────────────────────────────
function clearCompleted() {
state.todos = state.todos.filter(t => !t.completed);
saveState();
render();
}
// ─── Add Button & Enter key ───────────────────────────────────
document.getElementById('addBtn')
.addEventListener('click', () => addTodo(document.getElementById('todoInput').value));
document.getElementById('todoInput')
.addEventListener('keydown', e => e.key === 'Enter' && addTodo(e.target.value));
document.getElementById('clearCompleted')
.addEventListener('click', clearCompleted);
Step 5 — Toggle & Filter
We use event delegation — one listener on the parent <ul> handles all clicks on dynamic todo items. We read
the data-action attribute to decide what to do:
// ─── Toggle Complete ──────────────────────────────────────────
function toggleTodo(id) {
state.todos = state.todos.map(t =>
t.id === id ? { ...t, completed: !t.completed } : t
);
saveState();
render();
}
// ─── Event Delegation on list ─────────────────────────────────
document.getElementById('todoList')
.addEventListener('click', e => {
const li = e.target.closest('[data-id]');
const action = e.target.dataset.action;
if (!li) return;
if (action === 'toggle') toggleTodo(li.dataset.id);
if (action === 'delete') deleteTodo(li.dataset.id);
});
// ─── Filter Buttons ───────────────────────────────────────────
document.getElementById('filterBar')
.addEventListener('click', e => {
if (!e.target.dataset.filter) return;
state.filter = e.target.dataset.filter;
render();
});
e.target.closest() to find
which item was affected — far more efficient.
Step 6 — Inline Edit & Polish
Double-clicking a task replaces the <span> with a focused <input>. Enter saves the edit, Escape cancels it. The
state is only updated if the user presses Enter:
// ─── Inline Edit ──────────────────────────────────────────────
document.getElementById('todoList')
.addEventListener('dblclick', e => {
if (e.target.dataset.action !== 'edit') return;
const span = e.target;
const li = span.closest('[data-id]');
const id = li.dataset.id;
const originalText = span.textContent;
// Replace span with input
const input = document.createElement('input');
input.type = 'text';
input.value = originalText;
input.className = 'todo-edit-input';
span.replaceWith(input);
input.focus();
input.select();
// Save on Enter
input.addEventListener('keydown', e => {
if (e.key === 'Enter') {
const newText = input.value.trim();
if (newText) {
state.todos = state.todos.map(t =>
t.id === id ? { ...t, text: newText } : t
);
saveState();
}
render();
}
if (e.key === 'Escape') render(); // cancel
});
// Save on blur too
input.addEventListener('blur', () => render());
});
Wiring It All Together
At the bottom of app.js, call loadState() and render()
to boot the app. This two-line init is all you need:
// ─── Boot ─────────────────────────────────────────────────────
loadState(); // restore todos from localStorage
render(); // paint initial UI
Features & JS Concepts Reference
Every feature in the app maps to a core JavaScript concept you've learned in earlier chapters:
| Feature | JS Concept | Chapter |
|---|---|---|
| Add todo on Enter | Event listener · keydown | Ch 43 |
| Render list from array | Array.map() · template literals | Ch 31, 9 |
| Filter (All/Active/Done) | Array.filter() | Ch 32 |
| Toggle completed | Array.map() · spread operator | Ch 32, 33 |
| Delete todo | Array.filter() | Ch 32 |
| Handle clicks on dynamic items | Event Delegation · closest() | Ch 44 |
| Persist data across refreshes | localStorage · JSON.stringify/parse | Ch 57, 66 |
| Inline edit todo text | DOM manipulation · replaceWith() | Ch 42 |
| Unique task IDs | Date.now() · Math.random() | Ch 10 |
| XSS-safe rendering | textContent vs innerHTML | Ch 42 |
Try It Yourself — Live Todo App
The live editor below contains the complete, fully working Todo App. Try adding tasks, checking them off, filtering, double-clicking to edit, and refreshing to see localStorage in action:
localStorage!
Challenge: Extend the App
Once the core app works, try adding these features to deepen your skills:
todos array order and
save.priority field
(high/medium/low) to the todo object. Render a colour-coded badge and allow
filtering by priority.dueDate field. Show
a warning badge when a task is overdue. Sort tasks by due date.Why do we use event delegation on the todo list instead of attaching a separate listener to each todo item?
- A single state object is the source of truth. Every action mutates state,
saves to localStorage, then calls
render(). - The render function reads state and rebuilds the DOM from scratch — predictable, easy to debug, and mirrors how modern frameworks work.
- Event delegation puts one click listener on the
<ul>parent;e.target.closest('[data-id]')finds which todo was clicked. localStorage+JSON.stringify/parseprovides zero-setup data persistence across page refreshes.- Always escape user input with
textContent(notinnerHTML) to prevent XSS attacks. - Inline editing replaces a
<span>with a focused<input>— Enter saves, Escape or blur cancels. - This project demonstrates DOM manipulation, event handling, array methods, destructuring, localStorage, and the spread operator all working together.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.