Yet Another JavaScript todo list Tutorial

By | 16th August 2017

So to refresh my JavaScript skills I decided to building a todo list that will storage your todo list in your browsers local storage and will allow you to delete and edit your list also.

Creating the html page
Firstly we are going to create the html page for this tutoial.

  • The below code we import JavaScript so that our code will work.
  • The onload getToDo will get our list from the local storage, we will talk more about this in a while.
  • The textarea will allow us to add items to the todo list.

Javascript Code
Now time to break down the javascript code for this. The line below adds a listener to the submit button from the html page we created, when the button is pressed it calls a function saveToDo.

The saveToDo function gets the current time and uses it as the id for the todo list item that’s being saved and it also gets the input of whats been entered on the html page into the textarea box.

The next part of the function checks if the toDoList exists in the local storage if not we create the array and add our todo list item to it and save it to local storage as a string by using JSON.Stringify since local storage only supports strings, if it does exist we get the string from local storage and we use JSON.parse to covert back to a array.

Then we we call getToDo() function to update the toDolist.

GetToDo()
This function gets the todo list from local storage and we loop over all the items in the array and using innerHTML property that allows us to manipulate the html page, each item will also have a delete button that when pressed will call deleteToDo function.

deleteToDo()
When this function is called the id of the button pressed is passed to the function which we use to locate the item in local storage. We loop over the array and if we find the item with the id equal to the id passed in to the function we will use the built in function in JavaScript called splice to remove that item from the array and then we re-save the new array to local storage and call getToDo() to update the page.

Also here is some css below if you want to make the page look a bit better.

After saving all this, it should be a fully working todolist.
All the code is over at github.
And a working demo can be seen here.

Source: New feed