Pressing Keys
When the user presses a key, the element they're typing in gets the event keydown (a key went down). Which key it was is in event.key:
const nameInput = document.querySelector("#name");
nameInput.addEventListener("keydown", function (event) {
console.log(event.key);
});Type Hi into the field and press Enter, and the console shows:
Shift
H
i
EnterA letter key gives its letter, a capital one with Shift held down. Other keys have names, which start with a capital letter: "Enter", "Escape", "Backspace", "ArrowUp", "Shift". The space bar gives a space, " ". When you don't know what a key is called, print event.key as above and press the key.
Apps often use Enter to confirm what was typed, and Escape to cancel it:
nameInput.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
greeting.textContent = `Hello, ${nameInput.value}!`;
} else if (event.key === "Escape") {
nameInput.value = "";
}
});The handler runs for every key, so it checks which one it was. For any other key, it does nothing, and the letters appear in the field as usual.
The field here isn't in a form. In a form, Enter in a field sends the whole form. You'll see what that means two exercises from now.
Instructions
When Enter is pressed in messageInput, add a new item to the end of messageList with You: and the message, for example You: Hi, Eva!, and empty the field. When the field is empty, Enter doesn't add anything.
When Escape is pressed, empty the field without sending the message.