Building a ToDo App with Vanilla JavaScript

In the world of web development, building a To - Do application is a classic and fundamental project. It serves as an excellent starting point for understanding how to manipulate the Document Object Model (DOM), handle user input, and manage data in JavaScript. Vanilla JavaScript, which refers to using JavaScript without any external libraries or frameworks, provides a pure and straightforward way to build such an application. This blog will guide you through the process of creating a To - Do app using Vanilla JavaScript, covering fundamental concepts, usage methods, common practices, and best practices.

Table of Contents

  1. Fundamental Concepts
  2. Setting Up the Project
  3. HTML Structure
  4. CSS Styling
  5. JavaScript Logic
  6. Common Practices
  7. Best Practices
  8. Conclusion
  9. References

Fundamental Concepts

DOM Manipulation

The Document Object Model (DOM) is a programming interface for HTML and XML documents. In the context of a To - Do app, we use DOM manipulation to create, read, update, and delete HTML elements. For example, when a user adds a new task, we create a new <li> element and append it to the <ul> list of tasks.

Event Handling

Events are actions that occur in the browser, such as a user clicking a button or pressing a key. In our To - Do app, we use event handling to listen for events like the click of the “Add” button or the deletion of a task.

Data Storage

We need to store the tasks somewhere. In a simple To - Do app, we can use an array in JavaScript to store the tasks. As the app grows, we might consider using more persistent storage options like local storage.

Setting Up the Project

Create a new directory for your project. Inside this directory, create three files: index.html, styles.css, and script.js.

HTML Structure

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>ToDo App</title>
</head>

<body>
    <h1>ToDo App</h1>
    <input type="text" id="taskInput" placeholder="Add a new task">
    <button id="addTaskButton">Add Task</button>
    <ul id="taskList"></ul>
    <script src="script.js"></script>
</body>

</html>

In this HTML code, we have a title, an input field for adding tasks, a button to add tasks, and an unordered list to display the tasks.

CSS Styling

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
}

h1 {
    text-align: center;
    color: #333;
}

#taskInput {
    padding: 10px;
    width: 70%;
    border: 1px solid #ccc;
    border-radius: 4px;
}

#addTaskButton {
    padding: 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

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

#taskList {
    list-style-type: none;
    padding: 0;
}

#taskList li {
    background-color: white;
    padding: 10px;
    margin: 5px 0;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

#taskList li button {
    background-color: #f44336;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#taskList li button:hover {
    background-color: #da190b;
}

This CSS code styles the app to make it look more presentable. It sets the font, background color, and styles the input field, button, and task list.

JavaScript Logic

// Get DOM elements
const taskInput = document.getElementById('taskInput');
const addTaskButton = document.getElementById('addTaskButton');
const taskList = document.getElementById('taskList');

// Array to store tasks
let tasks = [];

// Function to render tasks
function renderTasks() {
    taskList.innerHTML = '';
    tasks.forEach((task, index) => {
        const li = document.createElement('li');
        li.textContent = task;
        const deleteButton = document.createElement('button');
        deleteButton.textContent = 'Delete';
        deleteButton.addEventListener('click', () => {
            tasks.splice(index, 1);
            renderTasks();
        });
        li.appendChild(deleteButton);
        taskList.appendChild(li);
    });
}

// Function to add a new task
function addTask() {
    const task = taskInput.value.trim();
    if (task!== '') {
        tasks.push(task);
        taskInput.value = '';
        renderTasks();
    }
}

// Event listener for the add task button
addTaskButton.addEventListener('click', addTask);

// Event listener for the enter key in the input field
taskInput.addEventListener('keypress', (event) => {
    if (event.key === 'Enter') {
        addTask();
    }
});

In this JavaScript code, we first get the DOM elements we need. We then create an array to store the tasks. The renderTasks function clears the existing task list and then loops through the tasks array to create <li> elements for each task. The addTask function adds a new task to the tasks array and then calls renderTasks to update the display. We also add event listeners to the “Add” button and the input field to handle task addition.

Common Practices

  • Separation of Concerns: Separate the HTML, CSS, and JavaScript code into different files. This makes the code more organized and easier to maintain.
  • Event Delegation: Instead of adding event listeners to each individual task item, we can use event delegation to attach a single event listener to the parent element. This can improve performance, especially when dealing with a large number of elements.

Best Practices

  • Error Handling: Add error handling to your code. For example, when accessing DOM elements, check if they exist before using them.
  • Code Optimization: Minimize the number of DOM manipulations. Each DOM manipulation can be expensive, so try to batch them together if possible.
  • Use of Constants and Variables: Use const and let instead of var to declare variables. const is used for values that should not change, and let is used for values that can change.

Conclusion

Building a To - Do app with Vanilla JavaScript is a great way to learn fundamental JavaScript concepts such as DOM manipulation, event handling, and data storage. By following the steps outlined in this blog, you can create a functional To - Do app. Remember to use common and best practices to make your code more organized, efficient, and maintainable.

References