Interactive Web Pages

HTML defines the structure of a web page by using page elements as the building blocks. However, HTML by itself can not produce web page interactivity, that’s where JavaScript comes in.

Web programmers use JavaScript to make web pages dynamic and interactive. This powerful scripting language is encapsulated in its own HTML element: the <script> element. You can think of this <script> element as the door to JavaScript for HTML. This lesson will dig deeper into what the <script> element can do for your websites and best practices on how and where to insert JavaScript in your HTML files.

 

The <script> tag

The <script> element allows you to add JavaScript code inside an HTML file. Below, the <script> element embeds valid JavaScript code:

<h1>This is an embedded JS example</h1>
<script>
  function Hello() {
    alert (‘Hello World’);
  }
</script>

 

Frankly, without the <script> tag, websites would be unclickable and a bit boring.

The <script> element, like most elements in HTML, has an opening and closing angle bracket. The closing tag marks the end of the content inside of the <script> element. Just like the <style> tag used to embed CSS code, you use the <script> tag to embed valid JavaScript code.

The src attribute

Since you know how to use a <script> element with embedded code, let’s talk about linking code. Linking code is preferable because of a programming concept called Separation of Concerns (SoC). Instead of having messy code that is all in the same file, web developers separate their code into different files, making each “concern” easier to understand and more convenient when changes must be made.

Instead of writing JavaScript in our HTML file, we can write it in its own file, and then reference this code with a file path name. We will do this using an attribute that may jog your memory: the src attribute!

If this seems familiar, that’s because you may have been linking to external files with the <img> and <link> elements. The attribute is exactly the same, but now its value specifies the location of your script file.

If the file is in the same project folder, the src value will be a relative path name. Below is an example of a providing a relative path for a JavaScript file.

<script src=“./exampleScript.js”></script>

 

The <script> above would look for a file called exampleScript.js that is in the same folder/directory as our index.html file.

If you must refer to JavaScript hosted externally, or in a CDN, you can also link to that file location.

How are scripts loaded?

A quick recap: the <script> element allows HTML files to load and execute JavaScript. The JavaScript can either go embedded inside of the <script> tag or the script tag can reference an external file. Before we dive deeper, let’s take a moment to talk about how browsers parse HTML files into web pages. This informs where to include a <script> element inside your HTML file.

Browsers come equipped with HTML parsers that help browsers render the elements accordingly. Elements, including the <script> element, are by default, parsed in the order they appear in the HTML file. When the HTML parser encounters a <script> element, it loads the script then executes its contents before parsing the rest of the HTML. The two main points to note here are that:

  • The HTML parser does NOT process the next element in the HTML file until it loads and executes the <script> element, thus leading to a delay in load time and resulting in a poor user experience.
  • Additionally, scripts are loaded sequentially, so if one script depends on another script, they should be placed in that very order inside the HTML file.

The GIF below displays two scripts being loaded. The first script makes a Watering Can appear, the second script makes a Flower appear. This shows how scripts are loaded sequentially, and how they pause the HTML parser, which is why “Blooming” appears at the end.

Document Object Model

The Document Object Model, abbreviated DOM, is a powerful tree-like structure that allows programmers to conceptualize hierarchy and access the elements on a web page.

The DOM is one of the better-named acronyms in the field of Web Development. In fact, a useful way to understand what DOM does is by breaking down the acronym but out of order:

  • The DOM is a logical tree-like Model that organizes a web page’s HTML Document as an Object.

Note: There are other types of documents, such as XML and SVG, that are also modeled as DOM structures.

The DOM is a language-agnostic structure implemented by browsers to allow for web scripting languages like JavaScript, to access, modify, and update the structure of an HTML web page in an organized way.

For this reason, we like to think of the DOM as the link between an HTML web page and scripting languages.

The DOM as a Tree Structure

Tree-like modeling is used in many fields, including evolutionary science and data analytics. Perhaps you’re already familiar with the concept of family trees: these charts represent the familial relationships amongst the descendants of a given family name.

The DOM tree follows similar logic to that of a family tree. A family tree is made up of family members and their relationships to the family name. In computer science, we would call each family member a node.

We define a node as an intersecting point in a tree that contains data.

In the DOM tree, the top-most node is called the root node, and it represents the HTML document. The descendants of the root node are the HTML tags in the document, starting with the <html> tag followed by the <head> and <body> tags and so on.

Parent Child Relationships in the DOM

Following the metaphor of a family tree, let’s define some key terminology in the DOM hierarchy:

  • A parent node is the closet connected node to another node in the direction towards the root.
  • A child node is the closest connected node to another node in the direction away from the root.

Knowing these terms will allow you to understand and discuss the DOM as a tree-like structure. In fact, you will also see this terminology used when referring to the nesting structure of HTML code. Programmers refer to elements nested inside other elements as the children elements and parent elements respectively.

Nodes and Elements in the DOM

As mentioned, a node is the equivalent of each family member in a family tree. A node is an intersecting point in a tree that also contains data.

There are many different types of node objects in the DOM tree. when trying to modify a web page, the script will mostly interact with the DOM nodes of type element. Elements are the building units of HTML web pages, they contain everything between an opening tag and a closing tag. If the tag is a self-closing tag, then that is the element itself.

Attributes of Element Node

DOM element nodes model elements in an HTML document.

Much like an element in an HTML page, the DOM allows us to access a node’s attributes, such as its class, id, and inline style.

The document keyword

The Document Object Model, abbreviated DOM, is a powerful tree-like structure that organizes the elements on a web page and allows scripting languages to access them. This lesson will focus on some of the most useful methods and properties of the DOM Interface in JavaScript. This interface is implemented by every modern browser.

First things first! The document object in JavaScript is the door to the DOM structure. The document allows you to access the root node of the DOM tree. Before you can access a specific element in the page, first you must access the document structure itself. The document allows scripts to access children of the DOM as properties.

For example, if you wanted to access the <body> element in your script, you could access it as a property of the document by typing document.body. This property will return the body element of that DOM.

Similarly, you could access the <title> element with the .title property. See a comprehensive list of all document properties.

 

Tweak an Element

When using the DOM in your script to access an HTML element, you also have access to all of that element’s properties.

This includes the ability to modify the contents of the element as well as its attributes and properties— that can range from modifying the text inside a p element to assigning a new background color to a div.

You can access and set the contents of an element with the .innerHTML property.

For example, the following code reassigns the inner HTML of the body element to the text ‘The cat loves the dog’:

document.body.innerHTML = ‘The cat loves the dog.’;

 

The .innerHTML property can also add any valid HTML, including properly formatted elements. The following example assigns an h2 element as a child inside the <body> element:

document.body.innerHTML = ‘<h2>This is a heading</h2>’;

 

Select and Modify Elements

What if we wanted to select a specific element? The DOM interface allows us to access a specific element with CSS selectors. CSS selectors define the elements to which a set of CSS rules apply, but we can also use these same selectors to access DOM elements with our script! Selectors can include the name of the tag, a class, or an ID.

The .querySelector() method allows us to specify a CSS selector and then returns the first element that matches that selector. The following code would return the first paragraph in the document.

document.querySelector(‘p’);

 

You can also use other CSS selectors such as an element’s . class or its # ID.

Another option, if you want to access elements directly by their id, you can use the aptly named .getElementByID() function:

document.getElementById(‘bio’).innerHTML = ‘The description’;

 

The example chains so that it selects the element with an ID of ‘bio’ and set its .innerHTML to the text ‘The description’.

Style an element

Another way to modify an element is by changing its CSS style. The .style property of a DOM element provides access to the inline style of that HTML tag.

The syntax follows an element.style.property format, with the property representing a CSS property.

For example, the following code selects the first element with a class of blue and assigns blue as the background-color:

let blueElement = document.querySelector(‘.blue’);
blueElement.style.backgroundColor = ‘blue’;

 

Unlike CSS, the DOM style property does not implement a hyphen such as background-color, but rather camelcase notation backgroundColor.

The following chaining syntax would also work:

document.querySelector(‘.blue’).style.fontFamily = ‘Roboto’;

 

Create and Insert Elements

Just as the DOM allows scripts to modify existing elements, it also allows for the creation of new ones. The .createElement(tagName) method creates a new element based on the specified tag name. However, it does not append it to the document. It creates an empty element with no inner HTML.

In order to create an element and add it to the web page, you must assign it to be the child of an element that already exists on the DOM. We call this process appending. The .appendChild() method will add a child element as the last child node.

The following code creates a new paragraph element, adds text to the new element’s innerHTML, and appends it to the body of the document:

let paragraph = document.createElement(‘p’);
paragraph.innerHTML = ‘The text inside paragraph’;
document.body.appendChild(paragraph);

 

Unlike .innerHTML the .appendChild() method does not replace the content inside of the parent, in this case body. Rather, it appends the element as the last child of that parent.

Remove an Element

In addition to modifying or creating an element from scratch, the DOM also allows for the removal of an element. The .removeChild() method removes a specified child from a parent.

Because the .querySelector() method returns the first paragraph, the following code would remove the first paragraph in the document:

let paragraph = document.querySelector(‘p’);
document.body.removeChild(paragraph);

 

It’s possible to also specify a different parent with the .querySelector() method, as long as you remove an element nested within that parent element.

If you want to hide an element because it does not need to be loaded initially, the .hidden property allows you to hide it by assigning it as true or false:

document.getElementById(‘sign’).hidden = true;

 

The code above did not remove the element from the DOM, but rather hid it. This is not the same as setting the CSS visibility property to hidden. For a list of the best use cases for this property, read a list in the MDN documentation.

 

Interactivity with onclick

You can add interactivity to DOM elements by assigning a function to run based on an event.

Events can include anything from a click to a user mousing over an element.

The .onclick property allows you to assign a function to run on a click event on an element:

let element = document.getElementById(‘interact’);
element.onclick = function() { element.style.backgroundColor = ‘blue’ };

 

Traversing the DOM

In the DOM hierarchy, parent and children relationships are defined in relation to the position of the root node.

A parent node is the closest connected node to another node in the direction towards the root.

A child node is the closest connected node to another node in the direction away from the root.

These relationships follow the nesting structure present in HTML code. Elements nested within one HTML tag are children of that parent element.

Each DOM element node has a .parentNode and .children property. The property will return a list of the element’s children and return null if the element has no children.

The .firstChild property will grant access to the first child of that parent element.

What is an Event?

When you refresh your email inbox, double tap on a post, or scroll through a newsfeed — something cool happens in your browser. These actions are known as events!

Events on the web are user interactions and browser manipulations that you can program to trigger functionality. Some examples of events are:

  • A mouse clicking on a button
  • Webpage files loading in the browser
  • A user swiping right on an image

You can create interactivity on a website by assigning a function to respond to a specific event firing, or triggering. In this lesson, you’ll learn to use JavaScript with events to create dynamic websites.

“Firing” Events

After a specific event fires on a specific element in the document object model (or DOM), an event handler function can be created to run as a response. In this lesson, we will learn about event handler functions that modify and update DOM elements after an event fires.

Let’s compare this to something more familiar: a cuckoo clock is an example of programming with events! When the clock hands strike a new hour, the cuckoo bird responds with a whistle for each hour. For example, the cuckoo bird will whistle twice when the clock strikes 2 o’clock.

Event handler functions wait for their specific events to fire like the cuckoo bird in the clock awaiting the next hour. These functions can be used to change a DOM element’s color, text and much more!

Most events in the browser take place without being noticed — the events are undetected because there is no event handler associated with the event to execute an action. Event handlers are crucial for creating interactive websites with JavaScript.

Event Handler Registration

You’re doing great! Now it’s time to dive into using event handler functions to create interactivity.

JavaScript interprets registered events as event objects with properties and methods. When you create an event handler function on a specific event, you create a property of the event object.

An event handler function is registered as a property attached to the DOM element being interacted with, or the event target. Check out the syntax:

let eventTarget = document.getElementById(‘targetElement’);

eventTarget.onclick = function() {
  // this block of code will run
}

 

Let’s break this down!

 

  • First, we accessed the DOM element that serves as the event target by its ID using document.getElementById(‘targetElement’).
  • Then we created the event handler property which consists of the event target followed by the event name (the prefix on- and the event type.) In this example, we’re using the click event which fires when the user presses and releases a mouse button on a DOM element.

 

  1. Lastly, we assigned an event handler function to the property.

Event handlers can also be registered as an HTML element attribute, but you should always avoid inline JavaScript code in HTML files!

 

Adding Event Handlers

It’s best practice to create named event handler functions, instead of anonymous functions. Your code will remain organized and reusable this way, even if your code gets complex. Check out the syntax:

let eventHandlerFunction = function() {
  // this block of code will run
}

eventTarget.onclick = eventHandlerFunction;

 

The .addEventListener() method is another common syntax for registering event handlers. An event listener waits for a specific event to occur and calls a named event handler function to respond to it. This method requires two arguments:

  1. The event type as a string
  2. The event handler function

Check out the syntax of an .addEventListener() method with a click event:

eventTarget.addEventListener(‘click’, eventHandlerFunction);

 

You’ll want to use the .addEventListener() method to allow multiple event handlers to be registered to a single event without changing its other event handlers.

 

Removing Event Handlers

The .removeEventListener() method is used to reverse the .addEventListener() method. This method stops the code from “listening” for an event to fire when it no longer needs to. .removeEventListener also passes two arguments:

  1. The event type as a string
  2. The event handler function

Check out the syntax of a .removeEventListener() method with a click event:

eventTarget.removeEventListener(‘click’, eventHandlerFunction);

 

Because this method unregisters event handlers, it needs to identify which function to remove from the event. The event handler function passed to the .removeEventListener() method must be the same function of the corresponding .addEventListener().

 

Event Object Properties

JavaScript stores events as event objects with their related data and functionality as properties and methods. There are pre-determined properties associated with event objects. You can call these properties to see information about the event, for example:

 

  • the .target property to access the element that triggered the event.
  • the .type property to access the name of the event.
  • the .timeStamp property to access the number of milliseconds that passed since the document loaded and the event was triggered.

 

Event Types

Beyond the click event, there are all types of DOM events that can fire in a browser! It’s important to know most events in the DOM take place without being noticed because there are no event handlers connected to them.

It’s also important to know some registered events don’t depend on user interactions to fire. For instance, the load event fires after website files completely load in the browser.

Browsers can fire many other events without a user — you can check out a list of events on the MDN Events Reference page.

Many events need user interaction with the DOM to fire. One user interaction event you’ve become familiar with is the click event. A click event fires when the user presses and releases a mouse button on an element in the DOM.

In the rest of this lesson, you’ll explore more user interaction event types like the mouse and keyboard events. To explore more event types, check out the MDN Events Reference.

Mouse Events

When you click down or move the mouse device mouse events fire. Outside of the click event, there are other events that can be fired when using a mouse.

  • The mousedown event is fired when the user presses a mouse button down. This is different from a click event because mousedown doesn’t need the mouse button to be released to fire.
  • The mouseup event is fired when the user releases the mouse button. This is different from the click and mousedown events because mouseup doesn’t depend on the mouse button being pressed down to fire.
  • The mouseover event is fired when the mouse enters the content of an element.
  • The mouseout event is fired when the mouse leaves an element.

Keyboard Events

Another popular type of event is the keyboard event! keyboard events are triggered by user interaction with keyboard keys in the browser.

  • The keydown event is fired while a user presses a key down.
  • The keyup event is fired while a user releases a key.
  • The keypress event is fired when a user presses a key down and releases it. This is different from using keydown and keyup events together, because those are two complete events and keypress is one complete event.

Keyboard events have unique properties assigned to their event objects like the .key property that stores the values of the key pressed by the user. You can program the event handler function to react to a specific key, or react to any interaction with the keyboard.

Review

In this lesson, you manipulated a webpage structure by leveraging the Document Object Model interface in JavaScript.

Let’s review what we learned:

  • The document keyword grants access to the root of the DOM in JavaScript
  • The DOM Interface allows you to select a specific element with CSS selectors by using the .querySelector() method
  • You can also access an element directly by its ID with .getElementById()
  • The .innerHTML and .style properties allow you to modify an element by changing its contents or style respectively
  • You can create, append, and remove elements by using the .createElement(),.appendChild() and .removeChild() methods respectively
  • The .onclick property can add interactivity to a DOM element based on a click event
    • JavaScript engines register events as objects with properties and methods associated with them.
    • Event handlers are registered as properties of their event object.

 

  • Event object properties like .target, .type, and .timeStamp are used to provide information about the event.
  • The .addEventListener() method can be used to add multiple event handler functions to a single event.

 

The .removeEventListener() method stops specific event handlers from “listening” for specific events firing.