Lesson 8 - Introduction to DOM and events in JavaScript

JavaScript Basics Introduction to DOM and events in JavaScript

In the previous lesson, Functions in JavaScript, we learned how to use functions. Until now, we have successfully avoided the main use of JavaScript, which is a manipulation with website contents. This involves reading and changing the contents of a page in response to some actions from the user (e.g. pressing a button to compute an example or to show/hide a specific part of the site). Such active websites are then referred to as web applications rather than websites. We respond to events by using functions which we can already declare. Today, we're going to demonstrate how to create such web applications and program a very simple JavaScript calculator.

What is DOM

DOM is an abbreviation for the Document Object Model. It's a tree of the elements (objects) from which an HTML page is composed. We can change objects in DOM using JavaScript, and of course it results in changing the web page as well. Let's introduce a simple HTML document.

<!DOCTYPE html>
<html>
<head>
        <title>My website</title>
        <meta charset="utf-8" />
</head>
<body>
        <nav>
                <img src="logo.png" alt="logo" />
                <ul>
                        <li>References</li>
                        <li>Photos</li>
                </ul>
        </nav>
        <main>
                <article>
                        <p>Hello</p>
                        <p>Huge</p>
                        <p>World</p>
                </article>
        </main>
</body>
</html>

As we've already said, JavaScript sees the document as a tree of objects. In a very simple way, we could imagine the DOM for the document above as follows:

DOM in JavaScript

Some nodes are missing in the illustration (the entire <head> element, there are also text nodes missing, which is the element's text itself, for example in the <p> element), however, we can see how JavaScript perceives the page. We can traverse the tree and add new elements to its branches, change its elements, or remove them. In our calculator, we'll just select elements from the DOM by their ids. Whenever we want to work with DOM in JavaScript, we use the document object which has the appropriate methods for it.

Preparing an HTML page for the calculator

For our calculator, let's create a very simple web page, which will contain two <input> elements to enter the numbers and one <button> to perform the calculation. The calculator will only be able to add numbers, but it won't bother us for now.

<!DOCTYPE html>
<html lang="en-us">

<head>
        <meta charset="UTF-8">
        <title>Simple web calculator</title>
</head>

<body>
        <h1>Simple web calculator</h1>
        <input type="text" id="number1" size="5" /> + <input type="text" id="number2" size="5" />
        <button id="button">Add!</button>
        <script>
                // We're going to write our code here
        </script>
</body>

</html>

The resulting page looks like this:

Your page
localhost

Notice that we inserted our script after the inputs and buttons. It's because if we put it above the elements, it'd be executed when the form elements are not yet in the page and so it wouldn't be able to use them.

Selecting elements by id

We'll use the getElementById() method to select an element by its id. The method takes the element's id as a string parameter (in the parentheses). Our calculator will work with the button and the number inputs we've just created, so we'll store them all into variables.

let button = document.getElementById("button");
let number1 = document.getElementById("number1");
let number2 = document.getElementById("number2");

Each element has some properties, the input elements (which we use for numbers), for example, have the value property in which the value entered by the user is stored. Let's create an add() function, which will use the variables created above to get inputs' contents, add it as 2 numbers, and display the result using the alert() function as a popup window.

function add() {
        alert(number1.value + number2.value);
}

Events

Whenever something happens in our application (the user enters something, clicks somewhere, an error occurs, and so on ...), JavaScript will trigger event handlers. Events can be found as properties on individual DOM elements, starting always with on, for example, onclick is the click event. We'll use this event on our button and attach our add() function to it. This causes the function to be called each time the button is clicked.

button.onclick = add;

Of course, there are more properties like this, we can react to a situation when the mouse cursor is moving over the button and on a few more things. Note that when we assign a function somewhere, we don't write parentheses. Now, we have the calculator almost finished. The source code (of the JavaScript part) of the entire calculator follows:

let button = document.getElementById("button");
let number1 = document.getElementById("number1");
let number2 = document.getElementById("number2");

function add() {
        alert(number1.value + number2.value);
}

button.onclick = add;

As you've probably figured out, our calculator adds values from the inputs as strings. Which is logical because they are strings. So once we enter "10" + "20", it prints "1020" instead of 30. We can fix this easily by using the parseInt() function to convert text to a number. We'll modify the add() function to look as following:

function add() {
        alert(parseInt(number1.value) + parseInt(number2.value));
}

Our calculator now works as expected. In order to bring it to perfection, we'll make two more adjustments.

The onload event

In order to avoid having to worry if the script is at the end of the page, and if it runs not before the page is fully loaded, we'll use the onload event. It's a property of the window object and it's triggered when the whole page is loaded (including images and so on). We'll modify our code to run just after loading the page no matter in which part of the page it's embedded. To handle the events, we'll use anonymous functions this time, which we learned in the previous lesson.

window.onload = function() {
        let button = document.getElementById("button");
        let number1 = document.getElementById("number1");
        let number2 = document.getElementById("number2");

        button.onclick = function() {
                alert(parseInt(number1.value) + parseInt(number2.value));
        };
}

The application works just as well as before. You can try to move the script e.g. after the <body> tag, the application will work the same way, because the code is executed only when the whole page is loaded.

External files

We should ideally not see JavaScript in HTML files, because mixing multiple programming languages in a single file is almost always a bad practice. You know, for example, that CSS files are stored separately and then linked from HTML. When we do the same with JavaScript, we talk about unobtrusive JavaScript, a code that isn't a nuisance in HTML but is in separate files.

We'll create a js subfolder in the project folder. Then we'll put the entire code above into the js/calculator.js file (no longer with the <script> element) and completely remove the <script> element from the HTML code. In the page header (<head>), we'll only add the following line which links to the script:

<script src="js/calculator.js"></script>

Alternatively, scripts are sometimes inserted just before the </body> tag. For larger applications, we should ideally create a folder for JavaScript files, named e.g. scripts/ or js/. We'll omit this in some smaller apps which we'll create during this course. Today's calculator can be downloaded in the attachment as always in case you made a mistake somewhere. In the next lesson, DOM manipulation in JavaScript, we'll continue manipulating DOM elements.


 

Download

Downloaded 1x (1.43 kB)
Application includes source codes in language JavaScript

 

 

Article has been written for you by Michal Zurek
Avatar
Do you like this article?
1 votes
Thumbnail
Previous article
Functions in JavaScript
Thumbnail
All articles in this section
JavaScript basic constructs
Activities (4)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!