JavaScript for Complete Beginners - Session 2 - A Tour of DOM

Welcome back to Session 2 of Module JavaScript - JavaScript for Complete Beginners.

Goal

In Session 1, we accomplished the following:

In this session, we will continue to push forward toward building a calculator. Specifically, we will move toward "drawing" the calculator on the screen with JavaScript (i.e. a more complex "print something" on the screen).

Visualize the Calculator

Although we all know what a calculator looks like, it's important that we can visualize it with enough details for us to know what to code. On my computer, the following is the look of the standard calculator and a scientific calculator on my computer.

Standard Calculator Scientific Calculator

As we can see, there are the following elements:

For us to build out a calculator, the goal then is that at a minimum we need to replicate the standard calculator. Our next step is to figure out how to "print" the calculator onto the screen with JavaScript. Given that we are just starting to learn how to programming, this can be a tall order, but let's take it step by step. Let's figure out how we can print out a single button.

Let's Play With Developer Tools A Bit More

In order to print out a single button with JavaScript, we will need to continue to get familiarize with our programming environment. As stated before, your browser is a full-fledged programming environment, and we do ourselves favors to leverage it to the max for learning purposes.

Let's open up our index.html from Session 1, and let's load it up in Chrome. You'll see that Hello world! This is printed by my JavaScript code! showing in big bold letters in the browser.

If we right click on the page and then choose inspect, it'll open the Developer Tool, which we looked at the Console tab in Session 1. This time, let's take a look at the Element tab.

Open Chrome Developer Tool

In the Element tab, you will see what looks like your current HTML code, except that it's not just text, but rather actual structure that maps to the HTML. You can expand / collapse the elements that have children elements to show / hide them.

Developer Tool Element Tab

As you move your mouse cursor over one of the elements, you can actually see the corresponding element in the browser window getting "highlighted". Chrome is trying to be extremely helpful to you as a developer, so you can orient yourself.

Developer Tool Element Tab

Furthermore, you can change the html in the page from inside the Elements tab. For example, you can change the text of an element:

Change Text in Elements Tab

You can change the color of an element:

Change Color in Elements Tab

You can even add a new element:

Add Element in Elements Tab

All these are made possible, because of something called DOM (Document Object Model).

What Is DOM (Document Object Model)

When the browser opens an HTML and tries to show what the page looks like, it basically creates an memory-representation of the HTML document, so that the browser can manipulate it easily. The memory representation is called DOM, and when we are changing the text, the color, and add elements through the Developer Tool, we are in effect making changes to the DOM, which causes the browser to "redraw" the document to reflect the changes.

We can use JavaScript to achieve the same effect. After all, you won't be in front of your users to make changes to the DOM through the Developer Tool for them, so you want your program to do it for you. Let's learn how we can make changes to the DOM through JavaScript.

DOM is what's known as an API (Application Programming Interface), basically a document set of methods, approaches, to accomplish a goal / operation via programming, which in this particular case, it's the official way for you to programmatically interface with the HTML page loaded into the browser.

So let's get started to see how we can program DOM.

Again, the developer tool can give us a lot of hints. Let's try to type slowly the word document into the Console. After a couple of characters, you should start to a list of potential matches showing up right underneath your typing. This is Chrome trying to be helpful to you, and this particular feature is known as intelligent code completion.

Intelligent Code Completion

It can go further too, after you typed out document, type ., and then see a new list populated.

Intelligent Code Completion

The reason that there is a new list showing up is because document is what's known as an object, which is a structure that have additional properties and methods that can be accessed via the . operator in JavaScript.

We will give a more formal treatment of some of these concepts in the next Session. What dealing with abstract concepts, it's always good to start with a concrete example.

Developer Tool's code completion basically help us to discover what are the available properties under an object after we type in the . operator. That helps you narrow down what you are looking for very quickly.

Though, since we just get started, it's still quite overwhelming to just see that list, and we don't know most of them. That's completely okay. Nobody remembers the whole list. Instead of trying to memorize the API, developers learn to see the patterns in the API, and then use that to guide them toward finding what they want.

For example, earlier we were able to make change to the text of an element, that means the following:

With the above knowledge, we now know what the API must support, and hopefully it does so in a "sane" way, i.e. the name of the properties / methods that we need hopefully would be similar to what we just said above, instead of something completely different. I.e.,

So, let's see how we can find a particular element, let's find the p element that we added.

There are quite a few methods that can be used to get an element. The one that we will use for now is getElementsByTagName.

var paragraphs = document.getElementsByTagName('p'); // return an array of elements that have the tag name 'p'
var elt = paragraphs[0];

What does the above code mean?

  1. we declare a variable called paragraphs (notice the plural), and we assign (=) the value from the function call of document.getElementsByTagName('p') to it.
  2. we then declare another variable called elt, and then we assign the "0th" item of the paragraphs to it.

Notice how much longer the equivalent English is compared to the code? A lot of beginners want to code in English, hopefully this helps reduce that thought.

We haven't talked about any of these concepts at all, so let's give it a quick shot.

What Is a Variable

Remember in the last session we talked about identifier? An identifier is a name that allows you to reference what's referred to by the name. Although we didn't explain it too much, we can more or less think of it as an "address" of a mailbox, so when we are using the identifier, we know which mailbox we are talking about so we can retrieve the content inside the mailbox.

If an identifier is the address of a mailbox, then a variable is a newly created mailbox with a new name that you just give it.

So in the code above, we created two new "mailboxes", one named paragraphs, and the other named elt, and we use = to put things inside those mailbox. Then as long as the mailboxes are still "visible" (a mailbox can become invisible when it gets destroyed, or when it gets hidden by another mailbox with the same name - we will talk about this later), you can refer to what's inside by the name of the mailbox.

If you ever wonder why you need to create a variable - the reason is that you might want to do something with the value held by that variable later. You don't need to create a variable for a value if you don't have such a need, i.e.

document.getElementsByTagName('p');

is also valid, but you won't be able to work with the values returned by that function call.

What Is An Array

The value returned by document.getElementsByTagName('p'); is what's known as an array, which can be thought of as a "list" of things.

Strictly speaking, the value returned is like an array, but not exactly an array. The distinction doesn't matter for us at this time, but I mention this just so you won't get surprised as you get further when it comes up.

What is specific about arrays is that they have the following behaviors:

Therefore, in the above code, we first assign the resulting array to the paragraphs variable, which means that paragraphs variable now holds an array, whose items can be accessed by []. so when we type

var elt = paragraphs[0];

We are accessing the first element inside the array.

We could write code like that above because we know for certain that there is one p element in the DOM, and this code might not work for other DOM. As we get better at writing code, we want to write code that can work in many situations so we will need to account for potential differences.

Once we have the element, we can then try to do things with it. For example - to change the color, we will need to work with the style property (this is the property manipulated by the infamous CSS).

elt.style.color = '#ff0000'; // change it to RED in RGB scheme.

To change the text, we can use the textContent property.

elt.textContent = "This is the new text";

To add a new element - after all, we are very interested in creating buttons, we utilize document.createElement and then appendChild on the element that we want to add it to.

var button = document.createElement('button');
document.body.appendChild(button); // until we have a better place, put the element under the body element will make it visible.

Also remember, a button created this way will look very "skinny" as it doesn't have any text.

button.textContent = "Click Me";

Awesome! Now that we know how to create a button, we can create all of the buttons needed by our calculator.

What Happens When We Click on the Button?

Having a button is nice, but we need to go further - we want the button to do something when we click it. If you try to click on the button now, you'll see that besides showing that you have clicked it, it doesn't do anything else. And that's because we haven't told it to do anything yet.

Software basically only do what they are programmed to do, i.e. all features and bugs are programmed in (bugs are unexpected outcome of the program).

In order to make the button do something, we need to add what's known as an event listener to the click event.

We will cover this concept in more details later, for now, just know that when there is an event, and if there is an event listener for the event, the event listener will get called.

An event listener is a function that listens to a particular event, in this particular example, it'll be a click event on the button element.

button.addEventListener('click', function () {
  // let's just do something we know how to do, let's change the color of the paragraph.
  elt.style.color = '#00ff00'; // change it to green.
})

Now when you click on the button, voila, the element's color is now changed! With the ability to handle events, it means that we now also know how to handle the users clicking on any of the calculator buttons, we just need to put everything together.

Conclusion

There are quite a few concepts we go through quickly in this chapter. In this chapter the goal is to show what's possible, so that programming doesn't look like magic. We have learned how to navigate around the Developer Tool, and we have succeed in manipulating the DOM, as well as hooking up event listeners to perform operations based on user triggered events like clicks. We will revisit them in subsequent chapters in more details to help solidify the understandings.