1. Home
  2. Training Library
  3. Applied JavaScript: Building a To-do App, Part 1

Applied JavaScript: Building a To-do App, Part 1

Developed with
QA

Contents

keyboard_tab

The course is part of this learning path

Web Development Fundamentals - Javascript Primer
course-steps 5 lab-steps 1 description 1
play-arrow
Applied Javascript: Building a To-do App, Part 1
Overview
DifficultyBeginner
Duration11m
Students19
Ratings
5/5
star star star star star

Description

Part 1: Populating JSON (JavaScript Object Notation) data into an HTML page.

Transcript

Being able to use JavaScript is an important part of web development. In this video, we're going to look at applying the fundamentals of JavaScript by building a to-do app. Throughout the video, we'll be continuously adding functionality until we have a working app. We'll start with a basic HTML template, as you can see on the screen. We have added Bootstrap to the HTML head so we can implement a simple page layout along with clean user interface elements.

If you're unfamiliar with Bootstrap, pause the video and take the time to search online for Bootstrap beginner tutorials to see its full potential. Let's use a two-column layout. The left side will be used to show a list of to-dos, on the right-hand side, we're going to create a simple form that lets us add new to-dos to the list. We have some sample JSON data set up in a variable. For convenience, this uses lorem ipsum text as filler.

JSON is a text-based data format following JavaScript object syntax. It resembles JavaScript object literal syntax, but it can be used independently from JavaScript. Many programming environments feature the ability to read, parse, and generate JSON. So let's use JavaScript to read this data and turn it into an HTML list. Firstly, let's load the empty unordered list, or ul element, from our DOM into our JavaScript variable.

Then, we'll loop through each item in the JSON data variable and create an HTML list item, or li element, and add it to the unordered list. The code for this is shown on screen now. If we save this and refresh our browser page, we can see the list.

Now, we'll delete the first sample item as we don't need it going forward. If we save and refresh again, we can see the default list item has been removed. In this second section, we will add a delete button to each of our to-do items. This will allow us to delete items and keep our list tidy. We extend the cord as shown to generate a link element.

For the moment, we'll give it a blank href. We'll then append some CSS classes to control the styling. The classes you see here are all Bootstrap classes, which is going to make the link look like a button and give it an outer margin. We set the link text to delete. Once we've created this delete link element, we append it as a child to the list item generated above. Saving the code and refreshing the browser page shows the new delete buttons.

Changing the CSS classes, changes the appearance of buttons. You could experiment with different classes to see the effect in the buttons, if you wish to. Clicking on the buttons at this point would have no result. This is because we haven't wired them up to do anything. But, we can fix that. Let's add the code that adds event listeners for all elements in the page that have the Delete class added to them.

The event listener will activate when a Delete button is pressed. We can call this the deleteTodo function. The deleteTodo function identifies the parent list item element of the delete button that was pressed. Then, it removes the whole list item from the page DOM. This removes it from the list in our browser.

So, it's time to try out our delete button. Great, it works. We can now delete items from the list. Let's see what happens when we refresh the page. Our list has reset, and the item we deleted has reappeared. But why is this? Our deleted item has reappeared because we are not persisting our changes. We'll learn how to persist our changes later on in this tutorial.

It will do well to bear in mind that the approach we're taking with this app isn't the only way we could implement to-do app. In programming, there are always multiple ways of solving a problem. For example, if we were using a JavaScript library like jQuery, we could leverage the power of jQuery and replace some of the vanilla JavaScript that we've used here. We'll take a look at jQuery later on in this series.

Next, let's implement the ability to add a new to-do item to our list. We'll build a simple add form on the right-hand side of the page. We want to create an input field for the title of the to-do to be typed by the user, and then an Add button. The Add button has an onclick method set to newTodo, which we will implement shortly.

Again, we've used some Bootstrap classes to control the styling of these elements. Let's save our changes and see what this looks like in our browser. Much better. But this form doesn't do anything yet. If we try submitting the form, we may see an error in our console. This will all depend on the browser being used and the way it's been configured. Picking up on errors in our JavaScript console is a useful debugging trick. And normally, if our JavaScript isn't working for some reason, the console will often say why it isn't working as it should.

So let's try and implement this function. Here's the code we have used. You may notice that it's very similar to the code we use before to populate the list from the JSON data variable. It'd be best if we could reuse the same code rather than duplicating it. But we'll come back to fix or refactor this after we've got the app working.

Before we continue, let's make sure our work is saved. Then we refresh the browser to see if it works. Brilliant, it does. However, if we refresh the page again, our changes are lost because we're not persisting anything, but we'll solve this in a later step. As we mentioned earlier, there was a lot of redundant code.

Even though we can say that our code works, it's not clean code, and any redundant or duplicate code needs to be refactored to avoid repetition. This is going to make our code much easier to maintain, and less likely to break.

We want to adhere to the D-R-Y, or DRY programming approach, which stands for, don't repeat yourself. So let's get refactoring. Instead of duplicating all to-do creation of code, that's called when the page loads, it'd be ideal if we could simply loop over the JSON data and call the newTodo function. This may not be the most elegant approach, but it'll suffice for the purposes of this demo.

We'll need to make a couple of changes to make this work, as there are some slightly different references in each code block, as you can see highlighted here. Let's refactor. So now we have a refactored code. You'll see we've removed a large chunk of code within the JSON data for each loop. And we're making a call to the newTodo function and passing it the value of the to-do title we want to create.

The newTodo function, further down the page, now has a parameter in the function definition, so it can accept a todoTitle. An if statement inside this function checks whether the todoTitle has been passed in or not. If it hasn't, then we're assuming that the function is being called by the add new form, and we grab the value of a todoTitle from the text input field. If you need some time to understand the code, feel free to pause this video and review it in more detail.

Assuming we're happy with everything, we'll save our work and then refresh our page in the browser to check everything still works. Okay, so everything still works. The initial list of to-dos loads, and we can add new items using the Add form. Our code has been tidied up to limit the unnecessary repetition of the same code. But we have a problem. Part of the app is actually broken. If we add a new item, and then try to delete it, it doesn't work. Any newly created to-dos, don't delete. Why would this be? Let's check our code.

The code that wires up our delete buttons is triggered the first time the page loads, as shown here in our main JavaScript block. It looks through all buttons with a delete class attached to them and sets up an event listener. The problem with this is that when a new delete button is added to our page, it doesn't have an event listener setup. So what can we do to remedy this?

Let's try refactoring our code, so we can make sure any new delete buttons have an attached event listener. We'll first move our event listener setup code into a function, so it is encapsulated and reusable. We can then easily call it from anywhere we need to. We'll make a call to it in the main JavaScript code block to make sure it is triggered when the page loads. We'll also add it to the end of the newTodo function. Let's refresh and test. And it works. Now we've got a basic working app, we don't need our default JSON data anymore.

We can replace that with an empty array. Our app will then start with an empty list to which we can add our own to-do items. As a side note, it's worth knowing that you can log information to the JavaScript console from your own code. This can be useful for debugging, troubleshooting, and generally keeping an eye on what's going on with your code. Let's have an example to demonstrate what we mean. We can use the console.log function.

After saving our work, we can refresh the app in our browser, add a new to-do and check the JavaScript console to see a message has been logged. We can also log objects to the console as well as text. So let's log the list item object when we add it. This shows the full HTML object we've created, which we then add to the DOM of the page, so we can log anything to the console we want.