javascript · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One listener, three buttons. Banana is clicked. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<button class="fruit">Apple</button>
<button class="fruit">Banana</button>
<button class="fruit">Cherry</button>
<p id="picked">Pick a fruit</p> const picked = document.querySelector("#picked");
for (const button of document.querySelectorAll(".fruit")) {
button.addEventListener("click", (event) => {
picked.textContent = `You picked ${event.target.textContent}`;
});
}
your turn
Your turn. Send a chat message with Enter.
Fill in the event that fires when a key goes down, then the name of the key that sends the message. Press run, type something and press Enter.
the page your code works on
<input id="chat" placeholder="Say something, then press Enter">
<p id="last">No messages yet</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- pressing Enter sends the messagenot checked yet
fix it
Pressing Enter does nothing. Fix it!
the page your code works on
<input id="search" placeholder="Search for a film">
<p id="results">Press Enter to search</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- pressing Enter searches for Paddingtonnot checked yet
- The listener runs on every key, but the
ifnever says yes. Look at the key it waits for. - Key names are case-sensitive, and the Enter key's name starts with a capital letter.
- Change "enter" to "Enter" on line 4, then press run.
nailed it
you know exactly what happened. :D
- Catch the
eventparameter to read facts about an event. event.targetis the element the event happened to.keydownfires on a key press, andevent.keynames the key.
new words in your collection
- target
- keydown
This lesson isn’t saved. A free account remembers every lesson you finish.