How to Build a Basic To-Do List App Using JavaScript

The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a web page. You can access all the DOM elements on the website and dynamically create, read, update, and delete (CRUD) them using JavaScript.

This article will explain how you can perform CRUD operations on a to-do list using JavaScript and DOM manipulation. We expect you to know the basics of HTML and JavaScript before going through this article.

Understanding Basic DOM Manipulation

Let’s go through a simple example:



The submitButton variable has access to the HTML button in the above code. You have to add the click event listener on the button (by getting the element by its id of submit). When the button is clicked, the event is triggered,and the window displays a pop-up with the text: “The form has been submitted.”

Now that we’ve covered the basic idea of DOM manipulation, let’s proceed forward and dive into building the to-do app.

Building the Layout Using HTML and TailwindCSS

Let’s have a look at the HTML layout of this project. The input elements and the buttons have their respective ids in order to get access to these elements in the JavaScript file.

For the frontend design, this article uses TailwindCSS, a utility CSS framework. You can use TailwindCSS in your project by importing the CSS file from the CDN.


Related: Tailwind CSS vs. Bootstrap: Which Is a Better Framework?

Code:





To-Do List App












This is how our app looks after designing:

Adding Functionality With Javascript:

The first step is getting access to the elements by their ids using the method getElementById().

const text = document.getElementById("text");
const addTaskButton = document.getElementById("add-task-btn");
const saveTaskButton = document.getElementById("save-todo-btn");
const listBox = document.getElementById("listBox");
const saveInd = document.getElementById("saveIndex");

We need an array to store all the to-do tasks. Hence, we need to initialize one.

let todoArray = [];

Adding Items to the To-Do List

To add a task to the array, you need to push it to the todoArray and then display it on the webpage. For this to happen, a click event must be triggered on the add button.

addTaskButton.addEventListener("click", (e) => {
e.preventDefault();
let todo = localStorage.getItem("todo");
if (todo === null) {
todoArray = [];
} else {
todoArray = JSON.parse(todo);
}
todoArray.push(text.value);
text.value = "";
localStorage.setItem("todo", JSON.stringify(todoArray));
displayTodo();
});

You have to store the todoArray to the localStorage on every change (i.e. whenever a task is added, updated, or deleted).

In the above code, you have to fetch the array from the localStorage; if no array exists, we create a blank one. Then we push the newly added task to the todoArray and store the whole array again in localStorage.

Displaying the To-Do List Changes

After appending the value to the todoArray, you need to display it on the web page. This is done by using .innerHTML attribute.

We put the HTML for the to-do list inside a variable named htmlCode. Then, we loop through the todoArray and add each item to the htmlCode variable.

Once you are done looping through all the items, you need to assign the whole HTML code to the listBox element using the .innerHTML attribute.

So after pushing the new to-do list item to the array, we call the displayTodo() function which handles all of that as described:

function displayTodo() {
let todo = localStorage.getItem("todo");
if (todo === null) {
todoArray = [];
} else {
todoArray = JSON.parse(todo);
}
let htmlCode = "";
todoArray.forEach((list, ind) => {
htmlCode += `

${list}




`;
});
listBox.innerHTML = htmlCode;
}

You have to add two buttons—update and delete—for each item while appending the todo items to the variable htmlCode.

Deleting Items From the To-Do List

The delete button has an attribute method onclick() that passes the todo index as the parameter. On clicking the delete button, the deleteTodo() method will be executed.

In this method, you have to apply the splice() array method on the todoArray. The splice() method helps to delete the item at the specified index. After deleting the item, you have to store the changes to the localStorage and call the displayTodo() function to reflect changes on the web page.

function deleteTodo(ind) {
let todo = localStorage.getItem("todo");
todoArray = JSON.parse(todo);
todoArray.splice(ind, 1);
localStorage.setItem("todo", JSON.stringify(todoArray));
displayTodo();
}

Updating Items in the To-Do List

Each to-do list item has an edit button, just like the delete button. The edit button has an attribute method onclick(). On clicking the button, the edit method gets executed and passes the index as the parameter.

There are two HTML elements whose display properties are set to none:

  1. Input element with id saveIndex
  2. Button with the id save-task-btn

As soon as you click on the edit button, the input will have the text value that you want to update with. The saveTaskButton will be displayed instead of addTaskButton.

The HTML code consists of an input element with id saveIndex. You have to set its default style property of display as none. When the edit method is called, you set the value attribute of this element to the id, so you can reference it later when saving the updated task.

function edit(ind) {
saveInd.value = ind;
let todo = localStorage.getItem("todo");
todoArray = JSON.parse(todo);
text.value = todoArray[ind];
addTaskButton.style.display = "none";
saveTaskButton.style.display = "block";
}

Once you are done editing the text, you click on the saveTaskButton. On clicking the button, you retrieve the id of the text using the saveInd input. After retrieving the id, you can update the todoArray at that index and push the changes to the localStorage. Finally, we called the displayTodo() function to reflect changes on the web page.

saveTaskButton.addEventListener("click", () => {
let todo = localStorage.getItem("todo");
todoArray = JSON.parse(todo);
let id = saveInd.value;
todoArray[id] = text.value;
addTaskButton.style.display = "block";
saveTaskButton.style.display = "none";
text.value = "";
localStorage.setItem("todo", JSON.stringify(todoArray));
displayTodo();
});

Check One Item Off Your To-Do List

Now that you have completed the basic to-do list app, it's time for you to start building more exciting projects by yourself!

You can either build a game or a web application that you can use for your personal use. Building projects will help you build your skills and get a good grasp of JavaScript. Keep learning and building amazing projects as much as you can.

Want to build another JavaScript project? Here's a simple calculator web application that you can build with HTML, CSS, and JavaScript.

Author: MUO Staff

Source: MUO Staff.” How to Build a Basic To-Do List App Using JavaScript”. Retrieved From https://www.makeuseof.com/how-to-build-todo-list-app-using-javascript/

All Rights Of This Article Reserved To MakeUseOf

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: