Build a JavaScript To-Do List
In this project, you will learn how to create a practical To-Do List application using JavaScript. You will learn how to add tasks, display tasks, complete tasks, delete tasks and save tasks in the browser.
Project Introduction
A To-Do List is a simple productivity application where users can create and manage tasks.
What You Will Learn
- HTML input fields
- JavaScript arrays
- Functions
- DOM manipulation
- Click events
- Array methods
- Local Storage
Create the HTML Structure
First, create a container for the To-Do List.
<div class="todo-app">
<h1>
My To-Do List
</h1>
<div class="input-area">
<input
type="text"
id="taskInput"
placeholder="Enter a task"
>
<button onclick="addTask()">
Add
</button>
</div>
<ul id="taskList">
</ul>
</div>
Create the Input Field
The input field allows the user to type a task.
<input
type="text"
id="taskInput"
placeholder="Enter a task"
>
JavaScript can access this input using its ID.
const taskInput =
document.getElementById("taskInput");
Create the Add Button
The Add button will call the addTask() function.
<button onclick="addTask()">
Add Task
</button>
Create a Todo Array
An array can store multiple tasks.
let todos = [];
A task can also be stored as an object.
let task = {
text: "Learn JavaScript",
completed: false
};
Add a New Task
First, get the value entered by the user.
const text =
taskInput.value.trim();
Then check whether the input is empty.
if(text === ""){
return;
}
Now add the task to the array.
todos.push({
text: text,
completed: false
});
Display Tasks
JavaScript can create HTML elements dynamically.
function displayTasks(){
taskList.innerHTML = "";
todos.forEach(function(todo){
const li =
document.createElement("li");
li.textContent =
todo.text;
taskList.appendChild(li);
});
}
Delete a Task
We can use the array index to identify a task.
function deleteTask(index){
todos.splice(index, 1);
displayTasks();
}
The splice() method removes an item from an array.
Mark a Task as Completed
Every task has a completed property. We can change it when the user clicks a task.
todos[index].completed =
!todos[index].completed;
The exclamation mark ! reverses the Boolean value.
false → true true → false
Save Tasks Using Local Storage
Without storage, tasks disappear when the browser is refreshed. Local Storage allows us to save data in the browser.
Save Data
localStorage.setItem(
"todos",
JSON.stringify(todos)
);
Load Data
const saved =
localStorage.getItem("todos");
if(saved){
todos = JSON.parse(saved);
}
Complete Project Flow
Complete To-Do List Project
You have now learned the main concepts required to build a practical JavaScript To-Do List.
Tutorial Completed! 📝
Now open the complete working To-Do List project and test everything you have learned.
Run Complete Project Learn JavaScript Arrays