This section will focus on the most commonly used Web API — the Document Object Model (DOM) — an API that gives you programmatic access to the contents, style, and structure of an HTML page. It’s the API used to dynamically change the contents of a web page which allowed developers to program complex behaviors like ones found in web applications.
Here’s an example of changing a web page’s structure. Consider the following HTML:
These examples are a bit contrived though. After all, if someone really wanted
to appear before
Here’s an example that will display a different message depending on your local time. If you’re reading this before noon, the paragraph will say Good morning!, otherwise, it’ll say Good evening (or afternoon)!
The DOM also gives you access to the browser’s event system, which you can leverage to trigger code based on events like clicking on a button or scrolling past a certain area on the page. We’ll cover the event system in more detail next.
The browser’s event system is based on a programming design pattern called event-driven programming where the flow of a program is determined by events like mouse clicks, key presses, or even messages from other programs. The system consists of event listeners that listen for certain events and event handlers that execute code when certain events occur.
Using the DOM, you can add an event listener to an HTML element using a special function called addEventListener. addEventListener needs two inputs — the name of an event and a function containing the code that should be triggered when the event occurs. For example, here’s a button that adds items to a list whenever it’s clicked:
Pay close attention to the last lines of code:
const listAdderButton = document.querySelector(‘button’); listAdderButton.addEventListener(‘click’, addItemToList);
In the code above, listAdderButton.addEventListener adds an event listener to the button element. ‘click’ is the type of event — a mouse click — and addItemToList is a variable whose value is a function that generates an li element and adds it to the list.
To add an event listener to an HTML element, you need three values:
We've covered many concepts in this unit! It probably still feels overwhelming, and that's okay. The more you experiment with code, the easier it will be. If this intrigued you, we encourage you to keep learning. There are many online resources, college courses, or even full bootcamp programs like Devmountain offers. In the next, and final unit, we'll introduce you to some computer engineering concepts that many web developers leverage.