Build a JavaScript Todo App: Beginner DOM Project
Build a complete JavaScript todo app from scratch. Learn DOM manipulation, event handling, localStorage persistence, filtering, editing, and drag-and-drop reordering.
Building a todo app is one of the best ways to practice DOM manipulation, event handling, and data persistence. This project brings together everything you have learned about creating elements, event listeners, event delegation, and form handling into a single working application. You will build the app step by step, starting simple and adding features like editing, filtering, localStorage, and drag-and-drop reordering.
Project Overview
The finished todo app will support:
| Feature | What It Does |
|---|---|
| Add todos | Type text and press Enter or click a button |
| Mark complete | Toggle checkbox to strike through the todo |
| Delete todos | Remove individual items |
| Edit todos | Double-click to rename |
| Filter view | Show all, active, or completed todos |
| Count display | Show how many items remain |
| Clear completed | Bulk delete finished items |
| Persist data | Save to localStorage so todos survive page refresh |
Step 1: Set Up the HTML Structure
The app starts with a simple HTML shell. All dynamic content will be created with JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: system-ui, sans-serif; background: #f5f5f5; padding: 40px 20px; }
.todo-app { max-width: 500px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
.todo-header { padding: 20px; border-bottom: 1px solid #eee; }
.todo-header h1 { font-size: 24px; color: #333; margin-bottom: 12px; }
.todo-input-row { display: flex; gap: 8px; }
.todo-input-row input { flex: 1; padding: 10px 12px; border: 2px solid #ddd; border-radius: 6px; font-size: 16px; }
.todo-input-row input:focus { border-color: #4a90d9; outline: none; }
.todo-input-row button { padding: 10px 20px; background: #4a90d9; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; }
.todo-list { list-style: none; }
.todo-item { display: flex; align-items: center; padding: 12px 20px; border-bottom: 1px solid #eee; gap: 12px; }
.todo-item.completed .todo-text { text-decoration: line-through; color: #999; }
.todo-text { flex: 1; font-size: 16px; }
.todo-edit { flex: 1; font-size: 16px; padding: 4px 8px; border: 2px solid #4a90d9; border-radius: 4px; }
.delete-btn { background: none; border: none; color: #e74c3c; cursor: pointer; font-size: 18px; opacity: 0.5; }
.delete-btn:hover { opacity: 1; }
.todo-footer { display: flex; justify-content: space-between; align-items: center; padding: 12px 20px; font-size: 14px; color: #777; }
.filters { display: flex; gap: 8px; }
.filters button { background: none; border: 1px solid #ddd; padding: 4px 10px; border-radius: 4px; cursor: pointer; font-size: 13px; }
.filters button.active { border-color: #4a90d9; color: #4a90d9; }
.clear-completed { background: none; border: none; color: #e74c3c; cursor: pointer; font-size: 13px; }
.empty-state { padding: 40px 20px; text-align: center; color: #999; }
</style>
</head>
<body>
<div class="todo-app" id="app">
<div class="todo-header">
<h1>Todo App</h1>
<div class="todo-input-row">
<input type="text" id="todo-input" placeholder="What needs to be done?" autofocus>
<button id="add-btn">Add</button>
</div>
</div>
<ul class="todo-list" id="todo-list"></ul>
<div class="todo-footer" id="todo-footer" style="display: none;">
<span id="todo-count"></span>
<div class="filters">
<button class="active" data-filter="all">All</button>
<button data-filter="active">Active</button>
<button data-filter="completed">Completed</button>
</div>
<button class="clear-completed" id="clear-completed">Clear completed</button>
</div>
</div>
<script src="todo.js"></script>
</body>
</html>Step 2: Create the Data Model
Every todo has an id, text, and completed status. The data model is a simple array of objects:
// todo.js - Data model
let todos = [];
let currentFilter = "all";
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}
function addTodo(text) {
const todo = {
id: generateId(),
text: text.trim(),
completed: false,
createdAt: Date.now()
};
todos.unshift(todo); // Add to beginning
saveTodos();
render();
}
function deleteTodo(id) {
todos = todos.filter(todo => todo.id !== id);
saveTodos();
render();
}
function toggleTodo(id) {
const todo = todos.find(t => t.id === id);
if (todo) {
todo.completed = !todo.completed;
saveTodos();
render();
}
}
function editTodo(id, newText) {
const todo = todos.find(t => t.id === id);
if (todo && newText.trim()) {
todo.text = newText.trim();
saveTodos();
render();
}
}
function clearCompleted() {
todos = todos.filter(todo => !todo.completed);
saveTodos();
render();
}Step 3: Render the Todo List
The render function creates DOM elements for each todo and updates the display:
// DOM references
const todoInput = document.getElementById("todo-input");
const todoList = document.getElementById("todo-list");
const todoFooter = document.getElementById("todo-footer");
const todoCount = document.getElementById("todo-count");
function getFilteredTodos() {
switch (currentFilter) {
case "active":
return todos.filter(t => !t.completed);
case "completed":
return todos.filter(t => t.completed);
default:
return todos;
}
}
function render() {
const filtered = getFilteredTodos();
// Clear existing list
todoList.innerHTML = "";
if (todos.length === 0) {
todoList.innerHTML = '<li class="empty-state">No todos yet. Add one above!</li>';
todoFooter.style.display = "none";
return;
}
todoFooter.style.display = "flex";
if (filtered.length === 0) {
todoList.innerHTML = '<li class="empty-state">No matching todos</li>';
} else {
filtered.forEach(todo => {
const li = createTodoElement(todo);
todoList.appendChild(li);
});
}
// Update count
const activeCount = todos.filter(t => !t.completed).length;
todoCount.textContent = `${activeCount} item${activeCount !== 1 ? "s" : ""} left`;
// Update clear completed button visibility
const hasCompleted = todos.some(t => t.completed);
document.getElementById("clear-completed").style.display = hasCompleted ? "inline" : "none";
// Update filter buttons
document.querySelectorAll(".filters button").forEach(btn => {
btn.classList.toggle("active", btn.dataset.filter === currentFilter);
});
}
function createTodoElement(todo) {
const li = document.createElement("li");
li.className = `todo-item${todo.completed ? " completed" : ""}`;
li.dataset.id = todo.id;
// Checkbox
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = todo.completed;
checkbox.className = "todo-checkbox";
// Text span
const textSpan = document.createElement("span");
textSpan.className = "todo-text";
textSpan.textContent = todo.text;
// Delete button
const deleteBtn = document.createElement("button");
deleteBtn.className = "delete-btn";
deleteBtn.textContent = "\u00D7"; // multiplication sign
deleteBtn.title = "Delete todo";
li.appendChild(checkbox);
li.appendChild(textSpan);
li.appendChild(deleteBtn);
return li;
}Step 4: Add Event Handling
Use event delegation on the list container instead of attaching listeners to every item:
// Add todo: button click and Enter key
document.getElementById("add-btn").addEventListener("click", () => {
const text = todoInput.value.trim();
if (text) {
addTodo(text);
todoInput.value = "";
todoInput.focus();
}
});
todoInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
const text = todoInput.value.trim();
if (text) {
addTodo(text);
todoInput.value = "";
}
}
});
// Event delegation for todo list actions
todoList.addEventListener("click", (e) => {
const item = e.target.closest(".todo-item");
if (!item) return;
const id = item.dataset.id;
// Checkbox click: toggle completed
if (e.target.classList.contains("todo-checkbox")) {
toggleTodo(id);
return;
}
// Delete button click
if (e.target.classList.contains("delete-btn")) {
deleteTodo(id);
return;
}
});
// Double-click to edit
todoList.addEventListener("dblclick", (e) => {
const textSpan = e.target.closest(".todo-text");
if (!textSpan) return;
const item = textSpan.closest(".todo-item");
const id = item.dataset.id;
const todo = todos.find(t => t.id === id);
if (!todo) return;
// Replace text span with input
const editInput = document.createElement("input");
editInput.type = "text";
editInput.className = "todo-edit";
editInput.value = todo.text;
textSpan.replaceWith(editInput);
editInput.focus();
editInput.select();
function finishEdit() {
const newText = editInput.value.trim();
if (newText && newText !== todo.text) {
editTodo(id, newText);
} else {
render(); // Restore original
}
}
editInput.addEventListener("blur", finishEdit);
editInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") finishEdit();
if (e.key === "Escape") render(); // Cancel edit
});
});
// Filter buttons
document.querySelector(".filters").addEventListener("click", (e) => {
const filterBtn = e.target.closest("[data-filter]");
if (!filterBtn) return;
currentFilter = filterBtn.dataset.filter;
render();
});
// Clear completed
document.getElementById("clear-completed").addEventListener("click", clearCompleted);Step 5: Add localStorage Persistence
Save todos so they survive page refreshes using localStorage:
const STORAGE_KEY = "todo-app-data";
function saveTodos() {
const data = JSON.stringify(todos);
localStorage.setItem(STORAGE_KEY, data);
}
function loadTodos() {
const data = localStorage.getItem(STORAGE_KEY);
if (data) {
try {
todos = JSON.parse(data);
} catch (err) {
console.error("Failed to parse saved todos:", err);
todos = [];
}
}
}
// Load on startup
loadTodos();
render();How localStorage Works
| Method | Purpose | Example |
|---|---|---|
setItem(key, value) | Save a string | localStorage.setItem("name", "John") |
getItem(key) | Read a string | localStorage.getItem("name") returns "John" |
removeItem(key) | Delete a key | localStorage.removeItem("name") |
clear() | Delete everything | localStorage.clear() |
localStorage only stores strings. Use JSON.stringify() to save objects and arrays, and JSON.parse() to read them back.
Step 6: Add Keyboard Shortcuts
document.addEventListener("keydown", (e) => {
// Ctrl+A or Cmd+A: focus the input (when not already focused)
if ((e.ctrlKey || e.metaKey) && e.key === "k") {
e.preventDefault();
todoInput.focus();
todoInput.select();
}
// Escape: clear input and blur
if (e.key === "Escape" && document.activeElement === todoInput) {
todoInput.value = "";
todoInput.blur();
}
});Step 7: Add Drag-and-Drop Reordering
Let users rearrange todos by dragging, using native HTML5 drag and drop:
let draggedItem = null;
function enableDragAndDrop() {
todoList.addEventListener("dragstart", (e) => {
const item = e.target.closest(".todo-item");
if (!item) return;
draggedItem = item;
item.style.opacity = "0.4";
e.dataTransfer.effectAllowed = "move";
});
todoList.addEventListener("dragend", (e) => {
const item = e.target.closest(".todo-item");
if (item) item.style.opacity = "1";
draggedItem = null;
// Remove all drag-over styles
todoList.querySelectorAll(".todo-item").forEach(i => {
i.style.borderTop = "";
});
});
todoList.addEventListener("dragover", (e) => {
e.preventDefault(); // Required to allow drop
e.dataTransfer.dropEffect = "move";
const item = e.target.closest(".todo-item");
if (!item || item === draggedItem) return;
// Clear all borders, then add to current target
todoList.querySelectorAll(".todo-item").forEach(i => {
i.style.borderTop = "";
});
item.style.borderTop = "2px solid #4a90d9";
});
todoList.addEventListener("drop", (e) => {
e.preventDefault();
const dropTarget = e.target.closest(".todo-item");
if (!dropTarget || !draggedItem || dropTarget === draggedItem) return;
const draggedId = draggedItem.dataset.id;
const targetId = dropTarget.dataset.id;
// Reorder the data array
const dragIndex = todos.findIndex(t => t.id === draggedId);
const targetIndex = todos.findIndex(t => t.id === targetId);
const [movedItem] = todos.splice(dragIndex, 1);
todos.splice(targetIndex, 0, movedItem);
saveTodos();
render();
});
}
// Update createTodoElement to make items draggable
function createTodoElement(todo) {
const li = document.createElement("li");
li.className = `todo-item${todo.completed ? " completed" : ""}`;
li.dataset.id = todo.id;
li.draggable = true; // Enable drag
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = todo.completed;
checkbox.className = "todo-checkbox";
const textSpan = document.createElement("span");
textSpan.className = "todo-text";
textSpan.textContent = todo.text;
const deleteBtn = document.createElement("button");
deleteBtn.className = "delete-btn";
deleteBtn.textContent = "\u00D7";
deleteBtn.title = "Delete todo";
li.appendChild(checkbox);
li.appendChild(textSpan);
li.appendChild(deleteBtn);
return li;
}
enableDragAndDrop();The Complete todo.js File
Here is the full JavaScript file with all features combined:
// State
let todos = [];
let currentFilter = "all";
const STORAGE_KEY = "todo-app-data";
let draggedItem = null;
// DOM references
const todoInput = document.getElementById("todo-input");
const addBtn = document.getElementById("add-btn");
const todoList = document.getElementById("todo-list");
const todoFooter = document.getElementById("todo-footer");
const todoCount = document.getElementById("todo-count");
const clearCompletedBtn = document.getElementById("clear-completed");
const filtersContainer = document.querySelector(".filters");
// Data functions
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}
function addTodo(text) {
todos.unshift({ id: generateId(), text: text.trim(), completed: false, createdAt: Date.now() });
saveTodos();
render();
}
function deleteTodo(id) {
todos = todos.filter(t => t.id !== id);
saveTodos();
render();
}
function toggleTodo(id) {
const todo = todos.find(t => t.id === id);
if (todo) { todo.completed = !todo.completed; saveTodos(); render(); }
}
function editTodo(id, newText) {
const todo = todos.find(t => t.id === id);
if (todo && newText.trim()) { todo.text = newText.trim(); saveTodos(); render(); }
}
function clearCompleted() {
todos = todos.filter(t => !t.completed);
saveTodos();
render();
}
// Persistence
function saveTodos() { localStorage.setItem(STORAGE_KEY, JSON.stringify(todos)); }
function loadTodos() {
const data = localStorage.getItem(STORAGE_KEY);
if (data) { try { todos = JSON.parse(data); } catch { todos = []; } }
}
// Rendering
function getFilteredTodos() {
if (currentFilter === "active") return todos.filter(t => !t.completed);
if (currentFilter === "completed") return todos.filter(t => t.completed);
return todos;
}
function createTodoElement(todo) {
const li = document.createElement("li");
li.className = `todo-item${todo.completed ? " completed" : ""}`;
li.dataset.id = todo.id;
li.draggable = true;
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = todo.completed;
checkbox.className = "todo-checkbox";
const textSpan = document.createElement("span");
textSpan.className = "todo-text";
textSpan.textContent = todo.text;
const deleteBtn = document.createElement("button");
deleteBtn.className = "delete-btn";
deleteBtn.textContent = "\u00D7";
deleteBtn.title = "Delete todo";
li.appendChild(checkbox);
li.appendChild(textSpan);
li.appendChild(deleteBtn);
return li;
}
function render() {
const filtered = getFilteredTodos();
todoList.innerHTML = "";
if (todos.length === 0) {
todoList.innerHTML = '<li class="empty-state">No todos yet. Add one above!</li>';
todoFooter.style.display = "none";
return;
}
todoFooter.style.display = "flex";
if (filtered.length === 0) {
todoList.innerHTML = '<li class="empty-state">No matching todos</li>';
} else {
filtered.forEach(todo => todoList.appendChild(createTodoElement(todo)));
}
const activeCount = todos.filter(t => !t.completed).length;
todoCount.textContent = `${activeCount} item${activeCount !== 1 ? "s" : ""} left`;
clearCompletedBtn.style.display = todos.some(t => t.completed) ? "inline" : "none";
filtersContainer.querySelectorAll("button").forEach(btn => {
btn.classList.toggle("active", btn.dataset.filter === currentFilter);
});
}
// Event handlers
addBtn.addEventListener("click", () => {
if (todoInput.value.trim()) { addTodo(todoInput.value); todoInput.value = ""; todoInput.focus(); }
});
todoInput.addEventListener("keydown", (e) => {
if (e.key === "Enter" && todoInput.value.trim()) { addTodo(todoInput.value); todoInput.value = ""; }
});
todoList.addEventListener("click", (e) => {
const item = e.target.closest(".todo-item");
if (!item) return;
if (e.target.classList.contains("todo-checkbox")) toggleTodo(item.dataset.id);
if (e.target.classList.contains("delete-btn")) deleteTodo(item.dataset.id);
});
todoList.addEventListener("dblclick", (e) => {
const textSpan = e.target.closest(".todo-text");
if (!textSpan) return;
const item = textSpan.closest(".todo-item");
const todo = todos.find(t => t.id === item.dataset.id);
if (!todo) return;
const editInput = document.createElement("input");
editInput.type = "text";
editInput.className = "todo-edit";
editInput.value = todo.text;
textSpan.replaceWith(editInput);
editInput.focus();
editInput.select();
function finishEdit() { const v = editInput.value.trim(); if (v && v !== todo.text) editTodo(todo.id, v); else render(); }
editInput.addEventListener("blur", finishEdit);
editInput.addEventListener("keydown", (e) => { if (e.key === "Enter") finishEdit(); if (e.key === "Escape") render(); });
});
filtersContainer.addEventListener("click", (e) => {
const btn = e.target.closest("[data-filter]");
if (btn) { currentFilter = btn.dataset.filter; render(); }
});
clearCompletedBtn.addEventListener("click", clearCompleted);
// Drag and drop
todoList.addEventListener("dragstart", (e) => {
const item = e.target.closest(".todo-item");
if (item) { draggedItem = item; item.style.opacity = "0.4"; e.dataTransfer.effectAllowed = "move"; }
});
todoList.addEventListener("dragend", (e) => {
const item = e.target.closest(".todo-item");
if (item) item.style.opacity = "1";
draggedItem = null;
todoList.querySelectorAll(".todo-item").forEach(i => i.style.borderTop = "");
});
todoList.addEventListener("dragover", (e) => {
e.preventDefault();
const item = e.target.closest(".todo-item");
if (!item || item === draggedItem) return;
todoList.querySelectorAll(".todo-item").forEach(i => i.style.borderTop = "");
item.style.borderTop = "2px solid #4a90d9";
});
todoList.addEventListener("drop", (e) => {
e.preventDefault();
const target = e.target.closest(".todo-item");
if (!target || !draggedItem || target === draggedItem) return;
const di = todos.findIndex(t => t.id === draggedItem.dataset.id);
const ti = todos.findIndex(t => t.id === target.dataset.id);
const [moved] = todos.splice(di, 1);
todos.splice(ti, 0, moved);
saveTodos();
render();
});
// Keyboard shortcut
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === "k") { e.preventDefault(); todoInput.focus(); todoInput.select(); }
if (e.key === "Escape" && document.activeElement === todoInput) { todoInput.value = ""; todoInput.blur(); }
});
// Initialize
loadTodos();
render();Concepts Used in This Project
| Concept | Where Used | Related Topic |
|---|---|---|
| createElement | Building todo items | DOM creation |
| appendChild | Adding items to list | DOM insertion |
| Event delegation | List click/dblclick handlers | Event patterns |
| Event listeners | All interactions | DOM events |
| Click events | Buttons, checkboxes, filters | User input |
| Keyboard events | Enter to add, Escape to cancel | Keyboard handling |
| querySelector | Finding DOM elements | DOM selection |
| Array methods | filter, find, findIndex, some | Data manipulation |
| JSON methods | localStorage serialization | Data persistence |
| Template literals | Count display text | String building |
Extending the Project
Ideas for adding more features to practice additional concepts:
Priority Levels
function addTodo(text, priority = "normal") {
todos.unshift({
id: generateId(),
text: text.trim(),
completed: false,
priority, // "low", "normal", "high"
createdAt: Date.now()
});
saveTodos();
render();
}
// Add priority indicator in createTodoElement
const priorityDot = document.createElement("span");
priorityDot.className = `priority-dot priority-${todo.priority}`;
li.insertBefore(priorityDot, checkbox);Due Dates
function addTodo(text, dueDate = null) {
todos.unshift({
id: generateId(),
text: text.trim(),
completed: false,
dueDate, // ISO date string or null
createdAt: Date.now()
});
saveTodos();
render();
}
function isOverdue(todo) {
if (!todo.dueDate || todo.completed) return false;
return new Date(todo.dueDate) < new Date();
}Categories or Tags
function addTodo(text, tags = []) {
todos.unshift({
id: generateId(),
text: text.trim(),
completed: false,
tags,
createdAt: Date.now()
});
saveTodos();
render();
}
// Filter by tag
function getTodosByTag(tag) {
return todos.filter(t => t.tags.includes(tag));
}Rune AI
Key Insights
- Data drives the DOM: Keep todos in an array, and re-render the entire list from that array whenever data changes
- Event delegation handles dynamic content: One listener on the parent list handles clicks for all current and future todo items
- localStorage persists state: Stringify to save, parse to load, and always wrap JSON.parse in try/catch for safety
- Render function is the single source of truth: Every change goes through addTodo/deleteTodo/toggleTodo, which call saveTodos and render
- Progressive enhancement: Start with core features (add, toggle, delete) then layer on editing, filtering, drag-and-drop, and keyboard shortcuts
Frequently Asked Questions
Why use event delegation instead of adding listeners to each todo item?
Why does the app use unshift instead of push to add todos?
How does localStorage persist data between page reloads?
Why use JSON.stringify and JSON.parse with localStorage?
How can I add animations when adding or removing todos?
Conclusion
This todo app project combines DOM element creation, event delegation, form input handling, keyboard events, and localStorage persistence into one working application. The key patterns to remember are keeping a data model in sync with the DOM (render from data, not the other way around), using event delegation for dynamic lists, and saving state to localStorage on every change so nothing is lost on page refresh.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.