DEV Community

Cover image for Creating a TODO with JavaScript
Walter Nascimento
Walter Nascimento

Posted on

Creating a TODO with JavaScript

[clique aqui para português]

A task list is something that helps a lot in our chores, making it possible to list and organize which tasks to do, so we will create a task list using only HTML and JAVASCRIPT, and a small class in CSS.

CODE

First we will create the interface, we will do something simple, using only HTML.

<h1>Lista de tarefas</h1>

<form name="form_main">
  <label for="task">Tarefa: </label> 
  <input type="text" name="task" id="task" /> <br />
  <button type="button" onclick="add()">Add</button>
</form>

<fieldset>
  <legend>Tarefas:</legend>
  <ul>
    <li>Limpar casa</li>
    <li>Outras</li>
  </ul>
</fieldset>

In the HTML structure an input was created to receive our task and a button was also created that triggers the add() function.

We will also need a CSS class to give a 'streaky' effect to completed tasks.

.checked {
  text-decoration: line-through;
}

The checked class is used only to define text as 'streaky' when completing a task.

Now let’s create the add() function.

function add() {
  let li = document.createElement('LI');
  let input_value = document.form_main.task.value;
  let input_text = document.createTextNode(input_value);

  li.appendChild(input_text);
  document.querySelector('ul').appendChild(li);
  document.form_main.task.value = "";

  createCloseButton(li);
}

The add() function creates a new element (task) in the list.

Within the add() function, a call is made to the createCloseButton() function, which is the function we are going to create now.

function createCloseButton(li) {
  let span = document.createElement("SPAN");
  let txt = document.createTextNode("\u00D7");

  span.className = "close";
  span.appendChild(txt);
  li.appendChild(span);

  span.onclick = () => span.parentElement.style.display = "none";
}

In the createCloseButton function we create a span with an x, which when clicking the element is hidden.

As the list is already with some items we will create a loop to go through all the li and add the close button.

Finally, we will add a click event to all li, and when clicking add the class checked.

document.querySelectorAll('li').forEach(createCloseButton);

document.querySelector('ul').addEventListener('click', (e) => {
  if (e.target.tagName === 'LI')
    e.target.classList.toggle('checked');
});

ready as simple as that.

Demo

See the complete project working below.

Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).

Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Top comments (0)