×

javascript · level 2 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Your listener gets an event full of facts about what happened.

When the browser calls your listener, it hands over one argument: a bundle of facts about the event. Catch it with a parameter, usually called event, and read its properties.

is the element the event happened to, such as the exact button clicked. For a event, fired the moment a key goes down, event.key names the key, like "a", "Enter" or "ArrowUp".

One listener can serve many buttons this way, reading event.target.textContent to know which one was pressed.

<input id="answer" placeholder="Type, then press Enter">
<p id="said">Waiting...</p>
const answer = document.querySelector("#answer");
const said = document.querySelector("#said");
answer.addEventListener("keydown", (event) => {
  if (event.key === "Enter") {
    said.textContent = `You said: ${answer.value}`;
  }
});

Press run it to bring the page to life.

console

nothing logged yet

Click into the box first, so your key presses go to it.