JavaScript 12 · Make a button run your code

JavaScript lesson 12 of 50 · Early intermediate · About 30 minutes

Turn an arrival report into a scanner the player can control.

Pip pauses where stone paths branch toward a crystal-roof workshop, a hanging garden and a distant beacon.
Mission Add a button that increases the number of cloud creatures found every time it is activated.

Get ready

Open Complete checkpoint below. For a browser preview, put the HTML in your editor’s HTML panel and the JavaScript in its JavaScript panel. For a local file, put the HTML first in a new .html file, then put the JavaScript between <script> and </script> at the end. Save the file and open it in a browser.

Match the HTML to the JavaScript. HTML tags create the game’s controls and text. An id names one element. The code uses that name to find the element. A class groups elements for styling, while a data- attribute can carry a game value. A status area with aria-live lets compatible screen readers announce updates.

Player acts. Activate the scanner button. → Listener runs. Advance one array position. → Render again. Show the total and stop at the limit.
Player acts → Listener runs → Render again

Understand the JavaScript in this lesson

Language to look for button element, click events, event listeners, function references, disabled property.

1. Give the player a control

The button is an HTML element, just like the paragraph. type="button" makes its role clear and keeps it from submitting a form if you later move it inside one. Real buttons work with both a mouse and a keyboard. The initial report uses role="status" so assistive software can announce updates.

2. Store the current position

The array holds the four totals for our imaginary scanner. scanIndex starts at zero, the position of the first item. Use let because the index moves. scans.length - 1 gives the last allowed position, which is three when there are four items.

let scanIndex = 0;

3. Run only when the button is used

An event is something the browser reports, such as a click. addEventListener stores the function for the browser to run later. Pass scan without parentheses so JavaScript hands over the function itself. Writing scan() there would call it immediately.

button.addEventListener("click", scan);

4. Update the page from the new data

The function checks the limit before += adds one. render() then reads the new index and changes the report. It sets disabled to the true or false result of the comparison. The final standalone render() draws the starting view once, before any click.

button.disabled = scanIndex === scans.length - 1;
Follow what happens step by step
  1. Open the checkpoint.
    Cloud creatures found: 0.Why The final render() runs after the listener is set up.
  2. Activate the scanner three times.
    Cloud creatures found: 3. The button becomes disabled.Why Each click advances one array position and the last position is the limit.

Predict before you run What would the starting report show if render() were removed from the bottom?

Reveal the answer

The report starts empty and stays empty until a click invokes scan. The initial render connects the data to the page before the player acts.

Complete checkpoint

HTML · the page and controls

<section aria-labelledby="mission-title">
  <h2 id="mission-title">Sky Island Rescue · Cloud scanner</h2>
  <p id="report" role="status"></p>
  <button id="scan" type="button">Scan for cloud creatures</button>
</section>

JavaScript · the instructions

const scans = [0, 1, 2, 3];
let scanIndex = 0;

const report = document.querySelector("#report");
const button = document.querySelector("#scan");

function render() {
  report.textContent = "Cloud creatures found: " + scans[scanIndex];
  button.disabled = scanIndex === scans.length - 1;
}

function scan() {
  if (scanIndex < scans.length - 1) {
    scanIndex += 1;
    render();
  }
}

button.addEventListener("click", scan);
render();

Read the JavaScript line by line

Open a small group of lines while you read the complete checkpoint. Blank lines separate ideas. Closing braces mark the end of a block. An ellipsis here means you can read the rest in the full program.

Lines 1–19
Line 1 const scans = [0, 1, 2, 3];
Set up scans. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 2 let scanIndex = 0;
Set up scanIndex. Give this name a starting value that later code can change.
Line 4 const report = document.querySelector("#report");
Set up report. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 5 const button = document.querySelector("#scan");
Set up button. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 7 function render() {
Define render. The body runs when the function is called.
Line 8 report.textContent = "Cloud creatures found: " + scans[scanIndex];
Plus adds numbers or joins text, depending on its values. Work out what is inside the brackets first, then use it as the key or index.
Line 9 button.disabled = scanIndex === scans.length - 1;
The triple equals compares without converting the value’s type. Minus subtracts the right value.
Line 12 function scan() {
Define scan. The body runs when the function is called.
Line 13 if (scanIndex < scans.length - 1) {
Run this part when the test is truthy. Check whether the first value is less than the second. Minus subtracts the right value.
Line 14 scanIndex += 1;
Update the existing value with the operation shown.
Line 15 render();
Call render with the values inside the parentheses.
Line 19 button.addEventListener("click", scan);
Register a function the browser should call when the named event happens.
Lines 20–20
Line 20 render();
Call render with the values inside the parentheses.

Mission challenge

Add another total to the scans array and check whether the button stops at the new final index.

Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.