Definition of a To-Do list Defining to-do lists is not a very difficult task. It is, simply, a ‘things to do list' that can be created during your spare time. These lists can be generic and meant for grocery shopping or daily routines, or can be as individual lists for projects or tasks that require it. Your brain is for doing. Todo lists are important because every unfinished task you've made a commitment to causes stress. What's more, your brain knows its own limits, so as you add more and more unfinished tasks, your brain starts thinking that some of them aren't going to get finished – causing even more stress.
- To Do List Beautiful Todo Lists For Your Site 2017
- Todo List Website
- To Do List Beautiful Todo Lists For Your Site Website
If you're not completely turned off by the idea of building yet another todolist app, and you're relatively new to JavaScript and Front-end development,this tutorial is for you. Here's a live demoof what you'll be building.
- It contains their daily to-do lists, monthly budgets, and whimsical sketches-all within the confines of a single notebook. As such, it may inspire a more emotional attachment than a regular planner.
- A task that has been noted as one that must be completed, especially on a list. My to-do list has been growing longer every day. And: Noun todo (plural todos) (US) A task yet to be done; an item on a to-do list. You can use whichever you want, but be consistent.
- To do list with progress tracker. Keep track of your tasks with this basic to-do list template. Set the priority, status, start and due dates, percentage complete, and when it's complete it will automatically be marked Done! This is an accessible template.
Prerequisites
This tutorial assumes that you have a basic knowledge of JavaScript.Essentially, you need to know what variables, arrays, functions and objects are,but you do not need to have prior experience with building JavaScriptapplications.
Get started
The todo list app we'll build in this tutorial will be pretty basic. A user canadd a task, mark a task as completed and delete an already added task. I'llexplain how to build each feature, but you must follow along by typing thecode and running it on your end to get the most out of this tutorial.
I recommend using JSFiddle while working through thistutorial, but feel free to use other code playgrounds or your local text editorif you prefer. Without further ado, grab the markup and styles for the appon JSFiddle. If you're usingJSFiddle, you can hit the Fork button to create a new fiddle of your own.
Add a todo
The first thing we need to do is set up an array where we'll place the todo listitems. Each todo item will be an object with three properties: text
, a stringwhich holds whatever the user types into the text input, checked
, a booleanwhich helps us know if a task has been marked completed or not, and id
, aunique identifier for the item.
Once a new task is added, we'll create a new todo object, push it into thearray and render the value of the text
property on the screen. When a todo ismarked as completed, we'll toggle the checked
property to true
, and when theuser deletes a todo, we'll locate the todo item in the array using its id
andremove it.
Let's start by adding a todo item to our list. To do so, we need to listen forthe submit
event on the form element, and then invoke a new addTodo()
function when the form is submitted.
Update the JavaScript pane on JSFiddle to look like this:
By default, when a form is submitted, the browser will attempt to submit it to aserver which will cause a page refresh. To prevent that from happening, we canstop the default behaviour by listening for the submit
event on the form, andusing event.preventDefault()
.
Next, we select the text input andtrimits value to remove whitespace from the beginning and end of the string, andthen save it in a new variable called text
. If the text
variable is notequal to an empty string, we pass the text to the addTodo()
function which isdefined above the event listener.
Within the function, we create a new object for the task and add the propertiesI mentioned earlier. The text
property is set to the function argument,checked
is initialised to false
, and id
is initialised to the number ofmilliseconds elapsed since January 1, 1970. This id
will be unique for eachtodo item unless you can add more than one task in a millisecond, which I don'tthink is possible.
Finally, the task is pushed to the todoItems
array, and the array is logged tothe console. In the form event listener after addTodo(text)
, the value of thetext input is cleared by setting it to an empty string, and it's also focused sothat the user can add multiple items to the list without having to focus theinput over and over again.
Add a few todo items and view the todoItems
array in your browser console. Youwill see that each todo item is represented by an object in the array. If you'reusing JSFiddle, you may need to check the built-in console provided by JSFiddle.
Render the todo items
Once a new todo item is added to the todoItems
array, we want the app to beupdated with the item rendered on the screen. We can do this pretty easily byappending a new li
element for each item to the .js-todo-list
element in theDOM.
To achieve this, add a new renderTodo()
function above addTodo()
:
The renderTodo()
function takes a todo
object as its only parameter. Itconstructs a li
DOM node using thedocument.createElement
method. On the next line, the class
attribute is setto todo-item ${isChecked}
. The value of isChecked
will be an empty string ifthe checked
property in the todo
object is false
. Otherwise, it will be‘done'. You will see the effect of this ‘done' class in the next section.
Next, a data-key
attribute is also set on the li
element. It is set tothe id
property of the todo
object and will be used to locate a specifictodo item in the DOM later in the tutorial. Followingthat, the contents of the li
element are set using the innerHTML
method andfinally, the li element is inserted as the last child of the .js-todo-list
element.
Change the console.log(todoItems)
line in addTodo()
to renderTodo(todo)
asshown below so that the renderTodo()
function is invoked each time a new todoitem is added.
Try it out by adding a few todo items. They should all render on the page.
Take a breather and see the complete code at the end of this step.Mark a task as completed
Let's add the ability to mark a task as completed. To do so, we need to listenfor the click event on the checkbox and toggle the checked
property onthe corresponding todo item.
Add the following code at the bottom of the JavaScript pane to detect the todoitem that is being checked off:
Instead of listening for clicks on individual checkbox elements, we arelistening for clicks on the entire list container. When a click event occurs onthe list, a check is done to ensure that the element that was clicked is acheckbox. If so, the value of data-key
on the checkbox's parent element isextracted and passed to a new toggleDone()
function (shown below) which shouldbe placed below the addTodo()
function.
This function receives the key of the list item that was checked or uncheckedand finds the corresponding entry in the todoItems
array using thefindIndexmethod. Once we have the index of the todo item, we need to locate it in thetodoItems
array using bracket notation. The value of the checked
property onthe todo item is then set to the opposite value.
Finally, the renderTodo()
function is called with the todo object passed in.If you run the code now and try checking off an item, it will duplicate the todoitem instead of checking off the existing one.
To fix this, we need to check if the current todo item exists in the DOM first, and replace it with the updated node if it does.Change your renderTodo()
function as shown below:
First, the current todo item is selected. If it exists in the DOM, the element will be returned and subsequently replaced. Ifthe item does not exist (as is the case for new todo items), it will be addedat the end of the list.
Take a breather and see the complete code at the end of this step.Let's start by adding a todo item to our list. To do so, we need to listen forthe submit
event on the form element, and then invoke a new addTodo()
function when the form is submitted.
Update the JavaScript pane on JSFiddle to look like this:
By default, when a form is submitted, the browser will attempt to submit it to aserver which will cause a page refresh. To prevent that from happening, we canstop the default behaviour by listening for the submit
event on the form, andusing event.preventDefault()
.
Next, we select the text input andtrimits value to remove whitespace from the beginning and end of the string, andthen save it in a new variable called text
. If the text
variable is notequal to an empty string, we pass the text to the addTodo()
function which isdefined above the event listener.
Within the function, we create a new object for the task and add the propertiesI mentioned earlier. The text
property is set to the function argument,checked
is initialised to false
, and id
is initialised to the number ofmilliseconds elapsed since January 1, 1970. This id
will be unique for eachtodo item unless you can add more than one task in a millisecond, which I don'tthink is possible.
Finally, the task is pushed to the todoItems
array, and the array is logged tothe console. In the form event listener after addTodo(text)
, the value of thetext input is cleared by setting it to an empty string, and it's also focused sothat the user can add multiple items to the list without having to focus theinput over and over again.
Add a few todo items and view the todoItems
array in your browser console. Youwill see that each todo item is represented by an object in the array. If you'reusing JSFiddle, you may need to check the built-in console provided by JSFiddle.
Render the todo items
Once a new todo item is added to the todoItems
array, we want the app to beupdated with the item rendered on the screen. We can do this pretty easily byappending a new li
element for each item to the .js-todo-list
element in theDOM.
To achieve this, add a new renderTodo()
function above addTodo()
:
The renderTodo()
function takes a todo
object as its only parameter. Itconstructs a li
DOM node using thedocument.createElement
method. On the next line, the class
attribute is setto todo-item ${isChecked}
. The value of isChecked
will be an empty string ifthe checked
property in the todo
object is false
. Otherwise, it will be‘done'. You will see the effect of this ‘done' class in the next section.
Next, a data-key
attribute is also set on the li
element. It is set tothe id
property of the todo
object and will be used to locate a specifictodo item in the DOM later in the tutorial. Followingthat, the contents of the li
element are set using the innerHTML
method andfinally, the li element is inserted as the last child of the .js-todo-list
element.
Change the console.log(todoItems)
line in addTodo()
to renderTodo(todo)
asshown below so that the renderTodo()
function is invoked each time a new todoitem is added.
Try it out by adding a few todo items. They should all render on the page.
Take a breather and see the complete code at the end of this step.Mark a task as completed
Let's add the ability to mark a task as completed. To do so, we need to listenfor the click event on the checkbox and toggle the checked
property onthe corresponding todo item.
Add the following code at the bottom of the JavaScript pane to detect the todoitem that is being checked off:
Instead of listening for clicks on individual checkbox elements, we arelistening for clicks on the entire list container. When a click event occurs onthe list, a check is done to ensure that the element that was clicked is acheckbox. If so, the value of data-key
on the checkbox's parent element isextracted and passed to a new toggleDone()
function (shown below) which shouldbe placed below the addTodo()
function.
This function receives the key of the list item that was checked or uncheckedand finds the corresponding entry in the todoItems
array using thefindIndexmethod. Once we have the index of the todo item, we need to locate it in thetodoItems
array using bracket notation. The value of the checked
property onthe todo item is then set to the opposite value.
Finally, the renderTodo()
function is called with the todo object passed in.If you run the code now and try checking off an item, it will duplicate the todoitem instead of checking off the existing one.
To fix this, we need to check if the current todo item exists in the DOM first, and replace it with the updated node if it does.Change your renderTodo()
function as shown below:
First, the current todo item is selected. If it exists in the DOM, the element will be returned and subsequently replaced. Ifthe item does not exist (as is the case for new todo items), it will be addedat the end of the list.
Take a breather and see the complete code at the end of this step.Delete todo items
Similar to the way we implemented the last feature, we'll listen for clicks onthe .js-delete-todo
element, then grab the key of the parent and pass it offto a new deleteTodo
function which will remove the corresponding todo objectin todoItems
array send the todo item to renderTodo()
to be removed from theDOM.
First, let's detect when the delete button is clicked:
Next, create the deleteTodo()
function below toggleDone()
as shown below:
The renderTodo()
function also needs to be updated as follows:
Now, you should be able to delete tasks by clicking the delete button.
Take a breather and see the complete code at the end of this step.Add an empty state prompt
An empty state occurs when there is no data to show in the app. For example,when the user hasn't added a todo yet (first use) or when the user has clearedthe list. It is important to account for this state when designing anapplication.
Many apps use the empty state to show a prompt that tells the user what to do.Here is a real-world example of what a good empty state prompt looks like:
Once there are no tasks to display, we'll add a prompt that encourages the userto add a new task. This feature can be implemented with just HTML and CSS.
We will take advantage of the :empty
CSS selector todisplay the prompt conditionally only if no items exist in the list.
Add the following code for the empty state prompt in the HTML pane as shownbelow:
Then add some styles for the empty state in your CSS:
While this looks just fine, the problem is that the message persists even when atask has been added to the list. The intended behaviour is for the prompt todisappear once a todo has been added and only reappear when there are no moretasks to display.
This bit of CSS will give us what we want:
The .empty-state
element is hidden from view by default with display: none
and only comes into view when .todo-list
is empty. We're using the:empty selector todetect when .todo-list
is empty, and the sibling selector (+
) to target.empty-state
and apply display: flex
to it only when .todo-list
is empty.
A subtle bug
To Do List Beautiful Todo Lists For Your Site 2017
One issue I encountered while working on this tutorial is that the empty statewouldn't return into view when all existing tasks are deleted.
Apparently, some whitespace persists in the .todo-list
element even after allits child li
elements have been removed, so it's not considered to be emptyand the styles defined with the :empty
selector does not kick in. To fix thisissue, we need to clear any whitespace from the element in our JavaScriptcode. Modify the renderTodo()
function as follows:
The above code solves the problem, and the app now works as expected.
Todo List Website
Take a breather and see the complete code at the end of this step.Persist the application state
Our todo list app is pretty much complete at this point, but let's add one morefeature to make things a bit more interesting and realistic. At the moment, oncethe page is refreshed, all the todo items are cleared. Let's prevent this bypersisting the application state to the browser'slocalstorage.
Add this line at the top of your renderTodo()
function:
Only strings may be stored in the localStorage so we need to convert ourtodoItems
array to a JSON string first before passing it to the setItem
method which adds a new data item under the specified key.
Each time the renderTodo()
function is invoked, the value of todoItemsRef
inthe localStorage will be replaced with the current value of the todoItems
array. This way, the array and the corresponding localStorage reference is keptin sync.
You can test this out by opening your browser dev tools, navigate to theApplication tab and monitor the Local Storage section. If you're notusing Chrome, the dev tools may be organised differently.
The final step is to render any existing todo list items when the page isloaded. Add the following code snippet at the bottom of the JavaScript pane:
When the DOMContentLoaded
event is fired, we proceed to retrieve the value oftodoItemsRef
from the localStorage. If it exists, the JSON.parse
method isused to convert the JSON string back to its original array form and save it intodoItems
.
Following that, renderTodo()
is invoked for each todo object present in thearray. This causes any saved todo items to be rendered as soon as the pageloads.
Conclusion
In this tutorial, we successfully built a todo list app that allows auser to add new tasks, mark a task as completed and delete old ones. We alsodiscussed the importance of accounting for empty states when designing anapplication, then proceeded to talk about a potential problem when using the:empty
selector and how to fix it.
Finally, we discussed persisting the application state to the browser'slocalStorage and how to get around its limitations using JSON.stringify
andJSON.parse
. If a section or piece of code is not clear to you, feel free toleave a comment below and I'll get back to you as soon as possible.
To Do List Beautiful Todo Lists For Your Site Website
Thanks for reading, and happy coding!