How to Create a To-Do List Using JavaScript
Creating a to-do list application is one of the best ways to start learning JavaScript. It involves DOM manipulation, event handling, and working with local storage. In this tutorial, we'll guide you step-by-step to build a fully functional to-do list app.
To-Do List
Features of the To-Do List App
- Add new tasks.
- Mark tasks as completed.
- Delete tasks.
- Save tasks to local storage so they persist even after the page is refreshed.
Prerequisites
To follow this tutorial, you need:
- Basic knowledge of HTML, CSS, and JavaScript.
- A code editor (like VS Code).
- A web browser for testing.
Step 1: Set Up the HTML Structure
Start by creating a simple HTML file for the app. Here's the basic structure:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>To-Do List</title> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f4; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } #todo-app { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); width: 300px; } #todo-app h1 { text-align: center; } #todo-app input, #todo-app button { width: 100%; margin-bottom: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; } .delete-btn{ width:50% !important; } #todo-list { list-style-type: none; padding: 0; } .todo-item { display: flex; justify-content: space-between; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 5px; } .completed { text-decoration: line-through; color: #888; } </style> </head> <body> <div id="todo-app"> <h1>To-Do List</h1> <input type="text" id="todo-input" placeholder="Add a new task..." /> <button id="add-button">Add Task</button> <ul id="todo-list"></ul> </div> <script src="app.js"></script> </body> </html>
Step 2: Add JavaScript Functionality
Create a new JavaScript file called app.js and link it to your HTML file. Then, implement the following functionality:
1. Select Elements
Start by selecting the input field, button, and list elements:
const todoInput = document.getElementById('todo-input'); const addButton = document.getElementById('add-button'); const todoList = document.getElementById('todo-list');
2. Add a New Task
Write a function to add tasks when the "Add Task" button is clicked:
addButton.addEventListener('click', () => { const taskText = todoInput.value.trim(); if (taskText === '') { alert('Please enter a task!'); return; } addTask(taskText); todoInput.value = ''; // Clear input field }); function addTask(taskText) { const li = document.createElement('li'); li.className = 'todo-item'; li.innerHTML = ` <span>${taskText}</span> <button> class="delete-btn">Delete</button> `; li.querySelector('span').addEventListener('click', () => { li.querySelector('span').classList.toggle('completed'); }); li.querySelector('.delete-btn').addEventListener('click', () => { li.remove(); saveTasks(); }); todoList.appendChild(li); saveTasks(); }
3. Save Tasks to Local Storage
Save the current list of tasks to local storage:
function saveTasks() { const tasks = Array.from(todoList.children).map(item => ({ text: item.querySelector('span').textContent, completed: item.querySelector('span').classList.contains('completed') })); localStorage.setItem('tasks', JSON.stringify(tasks)); }
4. Load Tasks from Local Storage
Load tasks when the page is refreshed:
function loadTasks() { const tasks = JSON.parse(localStorage.getItem('tasks')) || []; tasks.forEach(task => { const li = document.createElement('li'); li.className = 'todo-item'; li.innerHTML = ` <span class="${task.completed ? 'completed' : ''}">${task.text}</span> <button class="delete-btn">Delete</button> `; li.querySelector('span').addEventListener('click', () => { li.querySelector('span').classList.toggle('completed'); saveTasks(); }); li.querySelector('.delete-btn').addEventListener('click', () => { li.remove(); saveTasks(); }); todoList.appendChild(li); }); } loadTasks();
Full JavaScript Code
Here's the complete app.js file:
const todoInput = document.getElementById('todo-input'); const addButton = document.getElementById('add-button'); const todoList = document.getElementById('todo-list'); addButton.addEventListener('click', () => { const taskText = todoInput.value.trim(); if (taskText === '') { alert('Please enter a task!'); return; } addTask(taskText); todoInput.value = ''; // Clear input field }); function addTask(taskText) { const li = document.createElement('li'); li.className = 'todo-item'; li.innerHTML = ` <span>${taskText}</span> <button class="delete-btn">Delete</button> `; li.querySelector('span').addEventListener('click', () => { li.querySelector('span').classList.toggle('completed'); }); li.querySelector('.delete-btn').addEventListener('click', () => { li.remove(); saveTasks(); }); todoList.appendChild(li); saveTasks(); } function saveTasks() { const tasks = Array.from(todoList.children).map(item => ({ text: item.querySelector('span').textContent, completed: item.querySelector('span').classList.contains('completed') })); localStorage.setItem('tasks', JSON.stringify(tasks)); } function loadTasks() { const tasks = JSON.parse(localStorage.getItem('tasks')) || []; tasks.forEach(task => { const li = document.createElement('li'); li.className = 'todo-item'; li.innerHTML = ` <span class="${task.completed ? 'completed' : ''}">${task.text}</span> <button class="delete-btn">Delete</button> `; li.querySelector('span').addEventListener('click', () => { li.querySelector('span').classList.toggle('completed'); saveTasks(); }); li.querySelector('.delete-btn').addEventListener('click', () => { li.remove(); saveTasks(); }); todoList.appendChild(li); }); } loadTasks();
Conclusion
Congratulations! You've successfully built a functional to-do list application using JavaScript. This project is a great foundation for learning DOM manipulation, event handling, and local storage. Try enhancing it with features like task editing, filtering tasks by status, or adding due dates. Happy coding! ?