Create a simple to-do list app
How to Create a Basic To-Do List App Using JavaScript
One of the best project ideas for JavaScript beginners is to create a simple to-do list app. To make our to-do list usable, we need to write JavaScript. As we can see in the image above, we need to add a new task, make it available to the to-do section, move it to the completed-tasks section if it is marked as complete, then delete all the visual display items from the to-do and the complete tasks after the clear button is clicked. Here is our own tutorial for JS beginners.
The Document Object Model DOM is the data representation of the objects that make up the structure and content of a web page. You can access all DOM elements on the website and dynamically create, read, update and delete CRUD 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.
Understand basic DOM manipulation
<button id=”submit”>Submit</button>
<script>
const submitButton = document.getElementById(“submit”);
submitButton.addEventListener(“click”, ()=>{
alert(“The form has been submitted”);
});
</script>
The submitButton variable has access to the HTML button in the code above. You need to add the click event listener on the button (fetching the element by its id from submit ). When the button is clicked, the event is triggered and the window displays a popup with the text: “The form has been submitted. »
Now that we've covered the basic idea of DOM manipulation, let's go ahead and dive into creating the application to do.
Build the layout using HTML and TailwindCSS
Let's take a look at the HTML layout of this project. Input elements and buttons have their respective identifiers in order to access 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.
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />
Related: Tailwind CSS vs Bootstrap: Which Framework is Better?
Coded:
<div class="h-100 w-full flex items-center justify-center bg-teal-lightest font-sans mt-20">
<div class="bg-white rounded shadow p-6 m-4 w-full lg:w-3/4 lg:max-w-lg">
<div class="mb-4">
<h1 class="text-3xl md:text-4xl text-indigo-600 font-medium mb-2">
To-Do List App
</h1>
<div class="flex mt-4">
<input class="shadow appearance-none border rounded w-full py-2 px-3 mr-4 text-grey-darker" name="text" id="text" placeholder="Add Todo" />
<input type="hidden" id="saveIndex" />
<button class="p-2 lg:px-4 md:mx-2 text-center border border-solid border-indigo-600 rounded text-white bg-indigo-600 transition-colors duration-300 mt-1 md:mt-0 md:ml-1" id="add-task-btn">Add</button>
<button class="p-2 lg:px-4 md:mx-2 text-center border border-solid border-indigo-600 rounded bg-indigo-600 text-white transition-colors duration-300 mt-1 md:mt-0 md:ml-1" style="display: none" id="save-todo-btn">Edit Todo</button>
</div>
</div>
<div id="listBox"></div>
</div>
</div>
Added functionality with JavaScript:
The first step is to access the elements by their ids using the getElementById() method.
<script>
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");
</script>
We need an array to store all the to-dos. Therefore, we need to initialize one.
let todoArray = [];
Adding items to the task 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 fired 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 should store the todoArray in the localStorage each time there is a change (i.e. each time a task is added, updated or deleted).
In the code above, you need to retrieve the array from localStorage; if no array exists, we create an empty one. Then we send the newly added task to the todoArray and store the whole array again in localStorage .
Viewing Task List Changes
After adding the value to the todoArray , you need to display it on the webpage. This is done using the .innerHTML attribute. We put the HTML code for the to-do list inside a variable named htmlCode . Next, we loop through the todoArray and add each element to the htmlCode variable.
Once you are done iterating through all the elements, you need to assign the full HTML code to the listBox element using the .innerHTML attribute. So, after pushing the new to-do list item into the array, we call the displayTodo() function which handles all of this 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 += `<div class='flex mb-4 items-center'>
<p class='w-full text-grey-darkest'>${list}</p>
<button onclick='edit(${ind})' class='flex-no-shrink p-2 ml-4 mr-2 border-2 rounded text-white text-grey bg-green-600'>Edit</button>
<button onclick='deleteTodo(${ind})' class='flex-no-shrink p-2 ml-2 border-2 rounded text-white bg-red-500'>Delete</button>
</div>`;
});
listBox.innerHTML = htmlCode;
}
You need to add two buttons – update and delete – for each item while adding the to-do items to the htmlCode variable.
Deleting To-Do List Items
The delete button has an onclick() attribute method that passes the todo index as a parameter. By clicking on the delete button, the deleteTodo() method will be executed.
In this method, you need to apply the splice() array method on the todoArray . The splice() method removes the element at the specified index. After deleting the item, you need to store the changes in the localStorage and call the displayTodo() function to reflect the changes on the webpage.
function deleteTodo(ind) {
let todo = localStorage.getItem("todo");
todoArray = JSON.parse(todo);
todoArray.splice(ind, 1);
localStorage.setItem("todo", JSON.stringify(todoArray));
displayTodo();
}
Updating To-Do List Items
Each item in the to-do list has an edit button, just like the delete button. The edit button has an onclick() attribute method. By clicking on the button, the edit method is executed and passes the index as a parameter.
In addition, there are two HTML elements whose display properties are set to none:
The input element with id saveIndex Button with id save-task-btn
As soon as you click the edit button, the entry will have the text value you want to update with. The saveTaskButton will be displayed instead of addTaskButton .
The HTML code also consists of an input element with the id saveIndex . You need to set its display default style property to none. When the edit method is called, you set the value attribute of this element to the ID, so that 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 can also click the saveTaskButton button. Clicking the button also retrieves the id of the text using the saveInd input. After retrieving the ID, you can update
todoArray to that index and push the changes to localStorage Finally, we called the displayTodo() function to reflect the 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 off an item on your to-do list
Now that you've completed the basic to-do list app, it's time for you can also start creating more exciting projects on your own!
You can create a game or web application that you can use for your personal use. Creating projects will help you develop your skills and gain a good understanding of JavaScript. Keep learning and building amazing projects as much as you can.
You can read this article to learn more about things to build with JavaScript