Todo list: Vanilla Javascript
Let’s create a todo list with vanilla Javascript
. You will learn how to handle the UI using vanilla Javascript
such as creating a new element, deleting an element, updating text, and more.
Create three files: index.js
, index.html
, and index.css
. We will primarily use Bootstrap
for styling our UI, but in case you need to write some custom styles, it’s nice to have this file. The HTML
file will define our content, and the Javascript
file will handle the dynamic part.
1. HTML structure
2. Basic HTML layout
Select elements
Start with selecting all elements and hide the input group (form). DOMContentLoaded
will ensure that HTML
content is ready.
Button event
Attach a click event to the button. When we want to add a new todo, we need to click the button to show the input. Additionally, we need to update the text when we switch between states — hiding and showing the form. Switching the states resets the value of the input.
Helpers
Add the helper functions. The getRemoveIcon
method creates a new span
with the text delete and the class material-icons. This is necessary to properly display the material icons. The removeButton
is used to select the remove button, and later we will attach a click event to it to delete the todo.
The setTotalNumber
is a helper function that sets the correct count if a todo is deleted or created.
The getText
function prepares a div
with the text that is passed to the function.
Create todo
Attach a click event to the plus icon. First, we check if it is possible to add a new todo — the input must not be empty. Next, we will use the helper functions to create the necessary elements. After that, we will attach all the elements to the newly created li
element and apply some styles from Bootstrap.
Lastly, we get all the todos (li
elements) and get the length. We pass this to our helper function, which sets the correct text in the p
element (below h1
).
This is how our HTML
content will look like in the browser.
Don’t forget to remove all the hard-coded li
tags from the list. They were only needed to check how our HTML
would look like.
Delete todo
We will attach a click event to the remove icon. Because the remove icon is nested in the li
element, we need to refer to the parent element and remove it. Lastly, we need to update the text because one todo was removed.
Repository: here
Thank you for taking the time to read my article. I appreciate your interest in the topic and hope that it was informative. If you have any feedback or comments on the article, please don’t hesitate to share them with me.