Build a To-Do List with JavaScript: A Comprehensive Guide

A To-Do List is a simple yet powerful tool that helps users manage their tasks efficiently. In this article, we’ll guide you through building a To-Do List using JavaScript. We’ll cover the basics, advanced features, and provide code examples to help you understand the concepts better.

Table of Contents

  1. Introduction to To-Do List
  2. Basic Functionality
  3. Advanced Features
  4. Frequently Asked Questions

Introduction to To-Do List

A To-Do List is an application that allows users to add, view, and manage tasks. It’s a common project for beginners to learn JavaScript and web development. By the end of this guide, you’ll have a fully functional To-Do List application with the following features:
– Add new tasks
– Delete existing tasks
– Mark tasks as completed
– Persistent storage using localStorage

Basic Functionality

Step 1: HTML Structure

First, we’ll create the basic HTML structure for our To-Do List.

<!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>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>To-Do List</h1>
    <input type="text" id="taskInput" placeholder="Enter a new task">
    <button onclick="addTask()">Add Task</button>
    <ul id="taskList"></ul>
    <script src="script.js"></script>
</body>
</html>

Step 2: CSS Styling

Add some basic styling to make our To-Do List look good.

body {
    font-family: Arial, sans-serif;
    max-width: 500px;
    margin: 0 auto;
    padding: 20px;
}

input, button {
    padding: 10px;
    margin: 10px 0;
}

button {
    background-color: #4CAF50;
    color: white;
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    margin: 10px 0;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 5px;
}

li:hover {
    background-color: #ddd;
}

Step 3: JavaScript Functionality

Now, let’s add the JavaScript code to make our To-Do List functional.

// Get the task input and list elements
const taskInput = document.getElementById('taskInput');
const taskList = document.getElementById('taskList');

// Add task function
function addTask() {
    const taskText = taskInput.value.trim();

    if (taskText === '') {
        alert('Please enter a task!');
        return;
    }

    // Create new task element
    const task = document.createElement('li');
    task.className = 'task';

    // Create task content
    const taskContent = document.createElement('span');
    taskContent.textContent = taskText;

    // Create delete button
    const deleteBtn = document.createElement('button');
    deleteBtn.textContent = 'Delete';
    deleteBtn.onclick = deleteTask;

    // Append elements
    task.appendChild(taskContent);
    task.appendChild(deleteBtn);
    taskList.appendChild(task);

    // Clear input
    taskInput.value = '';
}

// Delete task function
function deleteTask(e) {
    const task = e.target.parentElement;
    task.remove();
}

Advanced Features

1. Mark Tasks as Completed

We can add a feature to mark tasks as completed by adding a checkbox.

<!-- Add this inside the li element in the addTask function -->
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.onclick = toggleTask;
checkbox.className = 'task-checkbox';
task.appendChild(checkbox);
function toggleTask(e) {
    const task = e.target.parentElement;
    task.classList.toggle('completed');
}
.completed {
    text-decoration: line-through;
    opacity: 0.5;
}

2. Persistent Storage using localStorage

To save tasks between sessions, we can use localStorage.

// Load tasks from localStorage when the page loads
window.onload = loadTasks;

// Save tasks to localStorage
function saveTasks() {
    const tasks = taskList.innerHTML;
    localStorage.setItem('tasks', tasks);
}

// Load tasks from localStorage
function loadTasks() {
    const tasks = localStorage.getItem('tasks');
    if (tasks) {
        taskList.innerHTML = tasks;
    }
}

3. Clear All Tasks

Add a button to clear all tasks.

<button onclick="clearAllTasks()">Clear All</button>
function clearAllTasks() {
    taskList.innerHTML = '';
    saveTasks();
}

Frequently Asked Questions

1. How do I save tasks permanently?

You can use localStorage to save tasks in the browser’s storage. This data persists even after the browser is closed.

2. Can I edit a task once it’s added?

Yes, you can add an edit button and modify the task text. Here’s an example:

// Create edit button
const editBtn = document.createElement('button');
editBtn.textContent = 'Edit';
editBtn.onclick = editTask;
task.appendChild(editBtn);

function editTask(e) {
    const task = e.target.parentElement;
    const taskContent = task.querySelector('span');
    const newText = prompt('Edit task:', taskContent.textContent);
    if (newText !== null) {
        taskContent.textContent = newText;
        saveTasks();
    }
}

3. How do I handle empty input?

We can check if the input is empty before adding a task. If it’s empty, show an alert.

if (taskText === '') {
    alert('Please enter a task!');
    return;
}

Conclusion

In this guide, we’ve built a fully functional To-Do List application using JavaScript. We started with the basic functionality and then added advanced features like marking tasks as completed, persistent storage using localStorage, and clearing all tasks. We also addressed some common questions and provided code examples to help you understand the concepts better.

We encourage you to experiment with the code, add more features, and customize the application to suit your needs. Happy coding!

Index
Scroll to Top