DEV Community

Cover image for πŸš€ Build a Simple To-Do App with JavaScript – A Step-by-Step Guide
Bhupesh Kumar
Bhupesh Kumar

Posted on

πŸš€ Build a Simple To-Do App with JavaScript – A Step-by-Step Guide

Managing daily tasks can be overwhelming, but what if you could build your own To-Do App?

In this beginner-friendly guide, we will walk through every step to create a fully functional To-Do App using HTML, CSS, and JavaScript.

What You’ll Learn:

  • How to build a simple To-Do App UI
  • Using JavaScript to add, view, complete, and delete tasks
  • Storing tasks persistently using localStorage
  • Writing clean HTML, CSS, and JavaScript code
  • Organizing your project for scalability & maintainability

GitHub Repo: To-Do App

To-Do App Screenshot 1

To-Do App Screenshot 2

πŸ“‚ Step 1: Project Setup

Before we start coding, let's set up our project structure.

  • Create a folder named to-do-app
  • Inside this folder, create the following files:

to-do-app/

  • index.html β†’ Main HTML structure
  • styles.css β†’ Styles for the app
  • script.js β†’ JavaScript logic
  • README.md β†’ Documentation

Now, let’s start coding! πŸš€


πŸ“œ Step 2: Creating the HTML Structure

We need a basic UI for our app, with buttons for adding, viewing, completing, and deleting tasks.

πŸ“Œ Create an index.html file and add this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minimal To-Do App</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

    <div class="container">
        <h2>πŸ“ To-Do App</h2>
        <p>Manage your tasks easily.</p>
        <div class="menu">
            <button class="view" onclick="viewTasks()">πŸ“‹ View Tasks</button>
            <button class="add" onclick="addTask()">βž• Add Task</button>
            <button class="complete" onclick="completeTask()">βœ… Complete Task</button>
            <button class="delete" onclick="deleteTask()">❌ Delete Task</button>
            <button class="exit" onclick="exitApp()">πŸšͺ Exit</button>
        </div>
    </div>

    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Understanding the Code

  • Buttons call JavaScript functions to perform actions.
  • CSS is linked (styles.css) for styling the app.
  • JavaScript is linked (script.js) to add functionality.

🎨 Step 3: Styling the App

Now, let’s make our app look clean and modern.

πŸ“Œ Create a styles.css file and add this code:

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap');

body {
    font-family: 'Inter', sans-serif;
    background-color: #f4f4f9;
    text-align: center;
    margin: 0;
    padding: 0;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* Centered App Container */
.container {
    background: #ffffff;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    width: 90%;
}

h2 {
    color: #333;
}

p {
    font-size: 14px;
    color: #666;
}

/* Buttons */
button {
    padding: 12px;
    font-size: 16px;
    border: none;
    cursor: pointer;
    width: 100%;
    border-radius: 8px;
    font-weight: 600;
    outline: none;
    transition: all 0.3s ease-in-out;
}

.view { background-color: #3498db; color: white; }
.add { background-color: #2ecc71; color: white; }
.complete { background-color: #f1c40f; color: black; }
.delete { background-color: #e74c3c; color: white; }
.exit { background-color: #95a5a6; color: white; }

button:hover {
    opacity: 0.85;
    transform: translateY(-2px);
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Uses Inter font for modern typography.
  • Adds hover effects on buttons.
  • Applies a centered white card layout for a clean UI.

πŸš€ Step 4: Adding JavaScript Logic

Now, let's add functionality to our To-Do App.

This guide explains the JavaScript logic used in the To-Do App. Each function plays an important role in managing tasks, storing them, and ensuring they persist even after refreshing the page.

The To-Do App allows users to:

  • Add tasks via prompt()
  • View tasks using alert()
  • Mark tasks as completed
  • Delete tasks
  • Store tasks persistently using localStorage

JavaScript is responsible for managing tasks, storing data, and handling user interactions.


Storing and Loading Tasks (localStorage)

Before working with tasks, they need to persist across browser sessions.

  • When the app loads, it retrieves saved tasks from localStorage, ensuring they don't disappear after a refresh.
  • If no tasks exist, an empty array is initialized.
  • localStorage.getItem("tasks") fetches saved tasks, and JSON.parse() converts the stored string back into an array.
  • localStorage.setItem("tasks", JSON.stringify(tasks)) updates the task list whenever a change is made.

Viewing Tasks (viewTasks())

This function displays all tasks in an alert box so users can see their to-do list.

  • If the task list is empty, an alert notifies the user that no tasks exist.
  • The function loops through all tasks and formats them:
    • Completed tasks show a checkmark [βœ”].
    • Pending tasks show an empty box [ ].
  • Finally, the formatted list is displayed in an alert box.

Key Concepts

  • Loops (forEach) iterate over the task list.
  • Ternary Operator (? :) checks if a task is completed.

Adding a Task (addTask())

Users can add a new task to their list using this function.

  • A prompt() asks the user for task input.
  • The task is stored as an object with { text: "task name", completed: false }.
  • The task is pushed into the array and saved in localStorage to ensure persistence.

Key Concepts

  • User input is taken via prompt().
  • Objects store task details (text and completion status).
  • .push() method adds a new task to the array.

Marking a Task as Completed (completeTask())

Users can mark tasks as completed or undo completion.

  • The task list is displayed.
  • The user enters the task number they want to complete.
  • The task’s completion status is toggled (if incomplete, it becomes complete and vice versa).
  • The updated list is saved in localStorage.

Key Concepts

  • Boolean toggling (!variable) flips true to false and vice versa.
  • parseInt() converts user input into a number.

Deleting a Task (deleteTask())

Users can remove a task from their to-do list.

  • The task list is displayed so users can see the task numbers.
  • The user enters the task number they want to delete.
  • The task is removed using .splice().
  • The updated task list is saved to localStorage.

Key Concepts

  • .splice(index, 1) removes one item at the given index.

Saving Tasks (saveTasks())

Whenever the task list is updated (added, completed, or deleted), it needs to be saved.

  • Converts the tasks array into a JSON string using JSON.stringify().
  • Saves it in localStorage using setItem().

Key Concept

  • localStorage only supports string data, so arrays and objects need conversion.

Exiting the App (exitApp())

This function simply displays a thank-you message when users exit the app.

Key Concept

  • Uses alert() to show a simple exit message.

Summary

By understanding this JavaScript code, you now know:

  • How JavaScript manipulates and stores data
  • How localStorage keeps data persistent
  • How user input is handled with prompt()
  • How tasks are dynamically updated in an array

Now, you fully understand the To-Do App’s JavaScript logic. Below is the full JavaScript code for reference:

πŸ“Œ Create a script.js file and add:

// Load tasks from localStorage
let tasks = JSON.parse(localStorage.getItem("tasks")) || [];

// Function to display tasks
function viewTasks() {
    if (tasks.length === 0) {
        alert("No tasks yet. Add one!");
        return;
    }
    let taskList = "Your To-Do List:\n";
    tasks.forEach((task, index) => {
        let status = task.completed ? "[βœ”]" : "[ ]";
        taskList += `${index + 1}. ${status} ${task.text}\n`;
    });
    alert(taskList);
}

// Function to add a task
function addTask() {
    let taskText = prompt("Enter your task:");
    if (taskText) {
        tasks.push({ text: taskText, completed: false });
        saveTasks();
        alert("Task added successfully!");
    }
}

// Function to mark a task as completed
function completeTask() {
    viewTasks();
    let taskNumber = parseInt(prompt("Enter task number to mark as completed:"));
    if (!isNaN(taskNumber) && taskNumber > 0 && taskNumber <= tasks.length) {
        tasks[taskNumber - 1].completed = !tasks[taskNumber - 1].completed;
        saveTasks();
        alert("Task updated!");
    }
}

// Function to delete a task
function deleteTask() {
    viewTasks();
    let taskNumber = parseInt(prompt("Enter task number to delete:"));
    if (!isNaN(taskNumber) && taskNumber > 0 && taskNumber <= tasks.length) {
        tasks.splice(taskNumber - 1, 1);
        saveTasks();
        alert("Task deleted!");
    }
}

// Function to save tasks to localStorage
function saveTasks() {
    localStorage.setItem("tasks", JSON.stringify(tasks));
}
Enter fullscreen mode Exit fullscreen mode

🎯 Summary

By completing this guide, you now have:

  • A working To-Do App
  • Basic JavaScript skills
  • LocalStorage implementation
  • A clean, responsive UI

πŸš€ Try it out, experiment, and enhance your skills! 😊

Top comments (0)