Tutorials JavaScript Project: Todo App
Ch 72 / 78
Chapter 72 Project 20 min read JavaScript

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.

What you'll learn
Structuring a real JavaScript project from scratch
DOM manipulation — create, read, update, delete
Persisting data with localStorage
Event delegation for dynamic elements
Filter & count logic (All / Active / Completed)
Inline editing & keyboard shortcuts
Component-style render functions
Clean code organisation with a state object

Project 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.

Add Tasks
Type a task and press Enter or click Add. Empty inputs are rejected with a shake animation.
Complete Tasks
Click the checkbox to toggle a task between active and completed. The count updates instantly.
Edit Tasks
Double-click any task to edit it inline. Press Enter to save, Escape to cancel.
Delete Tasks
Remove individual tasks with the delete button, or wipe all completed tasks at once.
Filter Tasks
Switch between All, Active, and Completed views. The active filter is highlighted.
Persist Data
Tasks survive a page refresh — saved and loaded from 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:

DOM Manipulation Event Listeners Event Delegation localStorage Array Methods Spread Operator Template Literals Arrow Functions Destructuring JSON.stringify / parse Date & IDs State Pattern

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.

📁 todo-app/
📄 index.html  — structure & markup
📄 style.css   — layout & visual design
📄 app.js     — all logic (state, render, events)
Project rule
We use a single state object as the source of truth. Every UI update is done by re-rendering from that state — never mutating the DOM directly. This mirrors how React and Vue work internally.

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:

Step 01
HTML Skeleton
Create the input field, add button, filter tabs, todo list container, and footer. All elements get an id or data-* attribute for easy JS selection.
Step 02
State & localStorage
Define the state object with a todos array and filter string. Write loadState() and saveState() to sync with localStorage.
Step 03
Render Function
Write a single render() function that re-draws the entire list from state every time data changes. Use innerHTML with a template literal loop.
Step 04
Add & Delete
Handle the form submit to add a new todo object { id, text, completed }. Use event delegation on the list container for delete buttons.
Step 05
Toggle & Filter
Toggle completed on checkbox click. Wire up filter buttons to update state.filter and re-render the correct subset of todos.
Step 06
Inline Edit & Polish
Add double-click to edit inline, Enter to save, Escape to cancel. Add "Clear Completed" button and active task count to the footer.

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:

index.html
<!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:

app.js — State setup
// ─── 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:

app.js — render()
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;
}
Why escHtml?
If a user types <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:

app.js — Add & Delete
// ─── 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:

app.js — Event Delegation & Filter
// ─── 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();
  });
Why event delegation?
Todo items are created and destroyed dynamically. Attaching listeners directly to each item means re-attaching them every render. Delegation puts one listener on the stable parent and uses 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:

app.js — Inline Edit
// ─── 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:

app.js — Boot
// ─── 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
⚡
Free Resource
Download our JavaScript Cheat Sheet
Syntax, built-in methods, ES6+ features — all on one page.
Get Sheet

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:

Live Editor — Todo App
✎ Editor
👁 Preview
Try these
Add 3 tasks → check one off → switch to "Active" filter → double-click a task to rename it → press Enter. Refresh the preview — your tasks are still there thanks to localStorage!
Advertisement

Challenge: Extend the App

Once the core app works, try adding these features to deepen your skills:

Drag to Reorder
Use the HTML5 Drag & Drop API to let users reorder tasks by dragging. Update the todos array order and save.
Priority Labels
Add a priority field (high/medium/low) to the todo object. Render a colour-coded badge and allow filtering by priority.
Due Dates
Add a dueDate field. Show a warning badge when a task is overdue. Sort tasks by due date.
Search / Filter
Add a live search input that filters the displayed list as the user types — no button click required.
Quick Check — Chapter 72

Why do we use event delegation on the todo list instead of attaching a separate listener to each todo item?

Chapter Summary
  • 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/parse provides zero-setup data persistence across page refreshes.
  • Always escape user input with textContent (not innerHTML) 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel