JavaScript 19 · Make navigation work from the keyboard

JavaScript lesson 19 of 50 · Early intermediate · About 45 minutes

Add shortcuts that reuse the same travel rules instead of creating a second movement system.

Pip pauses where stone paths branch toward a crystal-roof workshop, a hanging garden and a distant beacon.
Mission Let keys 1–4 activate destination controls while preserving normal keyboard browsing.

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.

Catch a key. Read the key inside the mission controls. → Find its button. Match the key and button positions. → Reuse the travel rule. Activate the same click listener.
Catch a key → Find its button → Reuse the travel rule

Understand the JavaScript in this lesson

Language to look for keydown events, event.key, indexOf, modifier checks, closest, click reuses a listener.

1. Give the shortcuts a home

The visible instructions tell players that keys 1 to 4 match the ordered destination buttons. Listen for keydown on the mission section while one of its inputs or controls has focus. Players can still press Tab to move between the regular buttons and use Enter or Space to activate one.

document.querySelector("section[aria-labelledby=mission-title]").addEventListener("keydown", handleShortcut);

2. Ignore keys meant for something else

The first guard skips combinations involving Alt, Control, Command or Shift and skips auto-repeat. || means any of those true values is enough to return. The next guard uses closest() to check whether the player is in a text entry element. That keeps these shortcuts from taking over typing.

if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) return;

3. Turn a key into a position

indexOf() finds the first matching position, starting at zero. If the pressed key is absent from the array, it returns minus one. The matching position in moveButtons gives the destination button. The HTML and the key list have the same order.

const index = keys.indexOf(event.key);

4. Take exactly the same action

Calling button.click() activates the existing listener, which still checks the route, battery and rescue state. The shortcut first checks disabled so it respects the end of a completed mission. Reports still go into the visible paragraph that has role="status".

if (!button.disabled) button.click();
Follow what happens step by step
  1. Tab to a mission button. From Sky Dock, press 2.
    Pip reaches Workshop.Why Key 2 maps to index 1, selecting the Workshop button.
  2. Release 2 and press 4.
    Pip reaches Beacon.Why The Beacon button uses the same travel check as an ordinary click.

Predict before you run What if you press 9, or press 4 after winning?

Reveal the answer

Nine has no entry, so the handler returns. After winning, the Beacon button is disabled and the shortcut leaves it alone.

Complete checkpoint

HTML · the page and controls

<section aria-labelledby="mission-title">
  <h2 id="mission-title">Sky Island Rescue · Island mission</h2>
  <p>Location: <span id="place"></span></p>
  <p>Energy: <span id="energy"></span></p>
  <p>Inventory: <span id="inventory"></span></p>
  <p id="shortcuts">Keyboard shortcuts 1–4 go to the matching destinations. Regular button controls also work.</p>
  <button type="button" data-destination="Sky Dock">1. Sky Dock</button>
  <button type="button" data-destination="Workshop">2. Workshop</button>
  <button type="button" data-destination="Garden">3. Garden</button>
  <button type="button" data-destination="Beacon">4. Beacon</button>
  <button id="charge" type="button">Recharge at Sky Dock</button>
  <button id="collect" type="button">Collect the local part</button>
  <button id="rescue" type="button">Activate the Beacon</button>
  <p id="report" role="status">Choose a connected destination.</p>
</section>

JavaScript · the instructions

const routes = {
  "Sky Dock": ["Workshop", "Garden"],
  Workshop: ["Sky Dock", "Beacon"],
  Garden: ["Sky Dock", "Beacon"],
  Beacon: ["Workshop", "Garden"]
};

const MAX_ENERGY = 6;

const partsAt = { Workshop: "Cog", Garden: "Lens" };

const needed = ["Cog", "Lens"];

const state = { place: "Sky Dock", energy: MAX_ENERGY, inventory: [], rescued: false };

const moveButtons = [...document.querySelectorAll("[data-destination]")];

function showMessage(message) {
  document.querySelector("#report").textContent = message;
}

function render() {
  document.querySelector("#place").textContent = state.place;
  document.querySelector("#energy").textContent = state.energy;
  document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
  for (const button of moveButtons) button.disabled = state.rescued;
  document.querySelector("#charge").disabled = state.rescued;
  document.querySelector("#collect").disabled = state.rescued;
  document.querySelector("#rescue").disabled = state.rescued;
}

function travel(event) {
  const destination = event.currentTarget.dataset.destination;
  if (state.rescued) return;
  if (!routes[state.place].includes(destination)) {
    showMessage("No route from " + state.place + " to " + destination + ".");
    return;
  }
  if (state.energy === 0) {
    showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Reload the page to try again."));
    return;
  }
  state.energy -= 1;
  state.place = destination;
  render();
  showMessage("Pip reaches " + destination + ".");
}

function recharge() {
  if (state.place !== "Sky Dock") {
    showMessage("Recharge is only available at Sky Dock.");
    return;
  }
  state.energy = MAX_ENERGY;
  render();
  showMessage("Pip’s battery is full.");
}

function collect() {
  const part = partsAt[state.place];
  if (!part) {
    showMessage("There is no part here.");
    return;
  }
  if (state.inventory.includes(part)) {
    showMessage("Pip already has the " + part + ".");
    return;
  }
  state.inventory.push(part);
  render();
  showMessage("Pip collects the " + part + ".");
}

function rescue() {
  if (state.place !== "Beacon") {
    showMessage("Travel to the Beacon first.");
    return;
  }
  const ready = needed.every(part => state.inventory.includes(part));
  if (!ready) {
    showMessage("The Beacon needs both the Cog and the Lens.");
    return;
  }
  state.rescued = true;
  render();
  showMessage("Beacon lit. The cloud creatures are safe!");
}

function handleShortcut(event) {
  if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) return;
  if (event.target.closest("input, textarea, select, [contenteditable]")) return;
  const keys = ["1", "2", "3", "4"];
  const index = keys.indexOf(event.key);
  if (index === -1) return;
  const button = moveButtons[index];
  if (!button.disabled) button.click();
}

for (const button of moveButtons) {
  button.addEventListener("click", travel);
}
document.querySelector("#charge").addEventListener("click", recharge);
document.querySelector("#collect").addEventListener("click", collect);
document.querySelector("#rescue").addEventListener("click", rescue);
document.querySelector("section[aria-labelledby=mission-title]").addEventListener("keydown", handleShortcut);
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–25
Lines 1–6 const routes = { "Sky Dock": ["Workshop", "Garden"], Workshop: ["Sky Dock", "Beacon"], Garden: ["Sky Dock", "Beacon"], Beacon: ["Workshop", "Garden"] };
Set up routes. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 8 const MAX_ENERGY = 6;
Set up MAX_ENERGY. Keep this name attached to the same value.
Line 10 const partsAt = { Workshop: "Cog", Garden: "Lens" };
Set up partsAt. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 12 const needed = ["Cog", "Lens"];
Set up needed. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 14 const state = { place: "Sky Dock", energy: MAX_ENERGY, inventory: [], rescued: false };
Set up state. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 16 const moveButtons = [...document.querySelectorAll("[data-destination]")];
Set up moveButtons. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0. Three dots unpack the existing entries here.
Line 18 function showMessage(message) {
Define showMessage. The body runs when the function is called, with inputs named message.
Line 19 document.querySelector("#report").textContent = message;
Replace the element’s displayed text. The browser treats the value as text.
Line 22 function render() {
Define render. The body runs when the function is called.
Line 23 document.querySelector("#place").textContent = state.place;
Replace the element’s displayed text. The browser treats the value as text.
Line 24 document.querySelector("#energy").textContent = state.energy;
Replace the element’s displayed text. The browser treats the value as text.
Line 25 document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
JavaScript tries the right side only when the left side is falsy. Combine array entries into a string, with the chosen separator between entries.
Lines 26–37
Line 26 for (const button of moveButtons)
Take one value at a time from this sequence and run the body with it.
Line 26 button.disabled = state.rescued;
Store the result in the name or property to the left.
Line 27 document.querySelector("#charge").disabled = state.rescued;
Store the result in the name or property to the left.
Line 28 document.querySelector("#collect").disabled = state.rescued;
Store the result in the name or property to the left.
Line 29 document.querySelector("#rescue").disabled = state.rescued;
Store the result in the name or property to the left.
Line 32 function travel(event) {
Define travel. The body runs when the function is called, with inputs named event.
Line 33 const destination = event.currentTarget.dataset.destination;
Set up destination. Keep this name attached to the same value.
Line 34 if (state.rescued)
Run this part when the test is truthy.
Line 34 return;
Leave this function immediately.
Line 35 if (!routes[state.place].includes(destination)) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Work out what is inside the brackets first, then use it as the key or index.
Line 36 showMessage("No route from " + state.place + " to " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 37 return;
Leave this function immediately.
Lines 39–54
Line 39 if (state.energy === 0) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 40 showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Reload the page to try again."));
Call showMessage with the values inside the parentheses.
Line 41 return;
Leave this function immediately.
Line 43 state.energy -= 1;
Update the existing value with the operation shown.
Line 44 state.place = destination;
Store the result in the name or property to the left.
Line 45 render();
Call render with the values inside the parentheses.
Line 46 showMessage("Pip reaches " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 49 function recharge() {
Define recharge. The body runs when the function is called.
Line 50 if (state.place !== "Sky Dock") {
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 51 showMessage("Recharge is only available at Sky Dock.");
Call showMessage with the values inside the parentheses.
Line 52 return;
Leave this function immediately.
Line 54 state.energy = MAX_ENERGY;
Store the result in the name or property to the left.
Lines 55–70
Line 55 render();
Call render with the values inside the parentheses.
Line 56 showMessage("Pip’s battery is full.");
Call showMessage with the values inside the parentheses.
Line 59 function collect() {
Define collect. The body runs when the function is called.
Line 60 const part = partsAt[state.place];
Set up part. Keep this name attached to the same value. Work out what is inside the brackets first, then use it as the key or index.
Line 61 if (!part) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 62 showMessage("There is no part here.");
Call showMessage with the values inside the parentheses.
Line 63 return;
Leave this function immediately.
Line 65 if (state.inventory.includes(part)) {
Run this part when the test is truthy. Check whether the collection contains the supplied item or text.
Line 66 showMessage("Pip already has the " + part + ".");
Call showMessage with the values inside the parentheses.
Line 67 return;
Leave this function immediately.
Line 69 state.inventory.push(part);
Add entries to the end of the array and return its new length.
Line 70 render();
Call render with the values inside the parentheses.
Lines 71–86
Line 71 showMessage("Pip collects the " + part + ".");
Call showMessage with the values inside the parentheses.
Line 74 function rescue() {
Define rescue. The body runs when the function is called.
Line 75 if (state.place !== "Beacon") {
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 76 showMessage("Travel to the Beacon first.");
Call showMessage with the values inside the parentheses.
Line 77 return;
Leave this function immediately.
Line 79 const ready = needed.every(part => state.inventory.includes(part));
Set up ready. Keep this name attached to the same value. Check whether every array entry passes the test.
Line 80 if (!ready) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 81 showMessage("The Beacon needs both the Cog and the Lens.");
Call showMessage with the values inside the parentheses.
Line 82 return;
Leave this function immediately.
Line 84 state.rescued = true;
Store the result in the name or property to the left.
Line 85 render();
Call render with the values inside the parentheses.
Line 86 showMessage("Beacon lit. The cloud creatures are safe!");
Call showMessage with the values inside the parentheses.
Lines 89–96
Line 89 function handleShortcut(event) {
Define handleShortcut. The body runs when the function is called, with inputs named event.
Line 90 if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat)
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy.
Line 90 return;
Leave this function immediately.
Line 91 if (event.target.closest("input, textarea, select, [contenteditable]"))
Run this part when the test is truthy. Look for the nearest matching element, starting at this element and then its ancestors.
Line 91 return;
Leave this function immediately.
Line 92 const keys = ["1", "2", "3", "4"];
Set up keys. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 93 const index = keys.indexOf(event.key);
Set up index. Keep this name attached to the same value. Find the first matching index, or return -1 when nothing matches.
Line 94 if (index === -1)
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 94 return;
Leave this function immediately.
Line 95 const button = moveButtons[index];
Set up button. Keep this name attached to the same value. Work out what is inside the brackets first, then use it as the key or index.
Line 96 if (!button.disabled)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 96 button.click();
Call button.click with the values inside the parentheses.
Lines 99–106
Line 99 for (const button of moveButtons) {
Take one value at a time from this sequence and run the body with it.
Line 100 button.addEventListener("click", travel);
Register a function the browser should call when the named event happens.
Line 102 document.querySelector("#charge").addEventListener("click", recharge);
Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 103 document.querySelector("#collect").addEventListener("click", collect);
Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 104 document.querySelector("#rescue").addEventListener("click", rescue);
Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 105 document.querySelector("section[aria-labelledby=mission-title]").addEventListener("keydown", handleShortcut);
Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 106 render();
Call render with the values inside the parentheses.

Mission challenge

Finish a whole mission using the number keys for movement and Enter on the collection and rescue controls.

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