Web basics · Easy · 10 min

Keyboard shortcuts for a prompt

Ctrl+Enter (or Cmd+Enter on a Mac) sends the prompt and Escape clears it. Every other key keeps working as usual.

Write handleKey(event) and register it with document.addEventListener('keydown', handleKey).

- Enter with ctrlKey or metaKey: call runPrompt() and stop the default action with event.preventDefault(). - Escape: empty the #prompt field. - Any other key, plain Enter included: do nothing.

runPrompt() already exists and counts runs in runCount.

Challenges 0/4

  • Ctrl+Enter runs once and prevents the default action
  • Cmd+Enter (metaKey) runs too
  • Plain Enter and other keys run nothing
  • Escape clears the field

function handleKey(event) {
  // Ctrl/Cmd + Enter: runPrompt() and event.preventDefault()
  // Escape: clear #prompt
}

document.addEventListener('keydown', handleKey);
Console output appears here (console.log).

Go deeper: the MDN reference →

This in production, with your data? Let's talk for 15 minutes →