From Zero to Deploy · Module 2 · Lesson 2.5

2.5 Events and the page, making clicks do things

How JavaScript finds an element on the page, changes its text, and reacts to clicks and to what the person types.

⏱ 25 min

The page is made of elements

So far the code has only talked to the console. In a real app, it changes the page: it swaps a piece of text, shows a number, paints the background. The page is made of elements written in HTML, like <h1> (a heading), <p> (a paragraph), and <button> (a button).

For JavaScript to change an element, it first has to find it. The most common way is to give the element an id (a unique name) in the HTML and look it up with document.getElementById:

Try it

Changing a piece of text

Result
Console
Nothing in the console yet. Use console.log(...) to show values here.

This example has two parts: the HTML (what shows on the page) and the JavaScript (what changes). textContent is the text inside the element. Putting a value into it changes what shows on screen.

Challenge: change the paragraph’s text too. Its id is info.

addEventListener: “when this happens, do that”

A page that changes by itself isn’t much use. What matters is reacting to what the person does: a click, a key, some typed text. Each of these is an event. And addEventListener says: when this event happens on this element, run this function.

Try it

Visit counter

Result
Console
Nothing in the console yet. Use console.log(...) to show values here.

Click the button a few times. Notice that the function doesn’t run when the page opens: it waits, and runs once per click. It’s an arrow function, just like the ones in the functions lesson.

Challenges:

  1. Add a reset button. In the HTML: <button id="reset">Reset</button>. In the JavaScript, a second addEventListener on that button that sets visits = 0 and updates the counter.
  2. When visits reach 5, show “You get a free coffee!” in the console. You need an if inside the click function.

Now it’s your turn. Write the code in the editor and click Run tests.

Exercise

Counter with a reset

Make the counter work, with the reset button. The HTML is ready: write only inside the <script>. Run shows the page so you can click it yourself; Run tests clicks the buttons for you.

HTML
Tests
Click Run tests to check your code.
Result

“Hello, world!” again

Remember the button that changes the background color, from the first module? Now you can read every line of it:

Try it

Hello, world!

Result
  • const colors = [...] is a list of colors.
  • let index = 0 is a variable that changes: it keeps the position of the current color.
  • addEventListener('click', () => { ... }) is an event that runs a function on every click.
  • index = (index + 1) % colors.length adds 1, and % (the remainder of a division) brings it back to 0 after the last color.
  • document.body.style.background = colors[index] takes the color at that position and paints the background.

Challenges:

  1. Add a new color to the list, for example '#c7d2fe'. Nothing else needs to change, because the code uses colors.length.
  2. Make the heading change too. In the HTML, give the heading an id: <h1 id="title">. In the JavaScript, inside the click, change its textContent to `Color ${index + 1} of ${colors.length}`.

Reacting to what the person types

Clicks aren’t the only event. The input event happens on every letter typed into a field, and .value is the text in the field at that moment:

Try it

Live greeting

Result
Console
Nothing in the console yet. Use console.log(...) to show values here.

Type your name, then delete it all. The if from the conditions lesson decides which greeting to show.

Challenge: if the name has more than 10 letters, show “What a long name!” at the end of the greeting. A piece of text also has .length, just like a list.

Exercise

The greeting

Make the greeting react to what the person types, including the long name from the challenge above. Write only inside the <script>, then type in the field on the result page.

HTML
Tests
Click Run tests to check your code.
Result

The button that does nothing

This is the bug you’ll run into most at the start: you click, and nothing happens.

Find the bug

Clicking the button does nothing, and the console shows “Cannot read properties of null (reading 'addEventListener')”. Which line has the problem?

Click the line with the problem.

Where you’ll see this in the course

  • In the 3D game, the keydown and keyup events say when a key was pressed and released. The game keeps track of it in an object, keys[e.code] = true, and on every frame checks which arrows are held down. On a phone, the on-screen buttons use the pointerdown event to do the same.
  • In the map app, the check-in buttons live inside the map’s popups. Instead of putting an event on each button, the app listens to clicks on the whole page with document.addEventListener('click', ...) and checks which button was clicked.
  • In the AI app, the choose-photo field uses the change event (written as onchange), which happens when the person picks a file.
Task

Practice

0 of 6 done

Checkpoint

Check what you learned

  1. What does addEventListener do?

  2. getElementById returned null. What does that mean?

  3. What does title.textContent = 'Hi' do?

  4. In this code, when does the console.log run?

    button.addEventListener('click', () => {
      console.log('Order placed!');
    });

End of the module

You’ve learned the five ideas that show up in every app: values and variables, functions, conditions and loops, lists and objects, and events. You don’t need to write a whole app by yourself, but now you can read the code the AI writes, understand what each part does, and notice when something is wrong.

In the next module, Spec first, you learn the method that makes the AI build exactly what you want.

Finished the lesson?

Mark it complete to track your progress.