To-Do List Using JavaScript
Tags: javascript, beginners, webdev, tutorial
Published: 2023-01-11 03:33:42

Hey guys, in this post, I'm going to walk you through a small JavaScript program that allows you to create a simple to-do list. 

_This builds on Wesbos JS30's day 15 challenge._

The reason I'm making this "guide" is to have a deeper understanding on different ways this can be done, as I'm currently working on a React-version off this as well.

The key functions of this app will be:
- Adding new tasks to the list
- Toggle Done/Incomplete
- Use LocalStorage to keep the data on page-reload.

---

First, let's take a quick look at the HTML code. 

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>To-Do LocalStorage</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <button class="wrapper">
      <h2>To-Do</h2>
      <p></p>
      <ul class="tasks">
        <li>Loading tasks...</li>
      </ul>
      <form class="add-tasks">
        <input type="text" name="task" placeholder="Task Name" required />
        <input type="submit" value="+ Add Task" />
      </form>
  </body>
</html>

```

Now, let's dive into the JavaScript code.

The first thing we do is select the form and the list elements on the website using document.querySelector(). We also use the localStorage.getTask() method to retrieve any existing tasks from Local Storage. If there are no tasks, the variable tasks will be an empty array.

```javascript
      const addTasks = document.querySelector(".add-tasks");
      const list = document.querySelector(".tasks");
      let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
```

## Add Task function

The next function is the addTask function, which is called when the user submits the form to add a new task to the list. 

The function takes in the event that is generated when the form is submitted. As the form is a submit, `event.prevenDefault();` will keep the page from refreshing. Then it gets the text entered in the form and creates a new object with that text, and sets the completion-status `done` to false.

```javascript
function addTask(event) {
        event.preventDefault();
        const text = this.querySelector("[name=task]").value; 

        const newTask = {
          text,
          done: false,
        };

        tasks.push(newTask);
        populateList(tasks, list);
        localStorage.setItem("tasks", JSON.stringify(tasks));
        this.reset();
      }
```

Then it adds this new task to the existing list of tasks, calls the `populateList` function to update the list on the website, saves the updated list of tasks in the browser's local storage, and finally resets the form so you can add more tasks.

## Populate List function

The next function is the populateList function, which updates the list displayed on the website. 

It first clears any existing content in the list, then uses map to generate a new one with the updated tasks, and finally transforms the new list into an array of strings for each task. This array is then joined into a single string and then set as the innerHTML of the list. 

```javascript
function populateList(tasks = [], list) {
        list.innerHTML = tasks
          .map((task, i) => {
            return `
          <li>
            <input type="checkbox" data-index=${i} id="task${i}"
            ${task.done ? "checked" : ""}/>
            <label for="task${i}">${task.text}</label>
          </li>
          `;
          })
          .join(""); 
      }
```

## Toggle Done function

The next function is the toggleDone function. This function is called when the user clicks on one of the checkboxes next to an task on the list. It checks if the element that was clicked on is an input element and if it isn't, it exits the function. It then retrieves the index of the clicked task from the dataset, and uses this to toggle the done property in the tasks list. Then, it saves the updated list of tasks in the browser's local storage and calls the populateList function to update the list on the website.

```javascript
  function toggleDone(e) {
        if (!e.target.matches("input")) return; // skips if target is not an input.
        // event delegation - chatGPT
        const element = e.target;
        const index = element.dataset.index;
        tasks[index].done = !tasks[index].done;
        localStorage.setItem("tasks", JSON.stringify(tasks));
        populateList(tasks, list);
      }
```

## Event Listener

The last part is event listeners. 
`addTasks.addEventListener("submit", addTask);`
listens for the 'submit' event on the form. 

`list.addEventListener("click", toggleDone); `listens for the 'click' event on the tasks list. When this event is fired, the toggleDone function is called.

`populateList(tasks, list)` will display the existing tasks on the website when the script first runs.

```javascript
addTasks.addEventListener("submit", addTask);

list.addEventListener("click", toggleDone);
populateList(tasks, list);
```
 
And that's it! A working todo-list.


![dancing](https://i.pinimg.com/originals/0d/39/d4/0d39d40172560dd857dc4f6f5c1d71c6.gif
)