CodingNic

Events & Keyboard Input

Add Keyboard Input

Events & Keyboard Input 25 min read

Add Keyboard Input

Task

Allow users to operate the calculator from the keyboard.

Open

Open:

js/ui.js

Listen for keyboard events and translate supported keys into calculator actions.

Add the keyboard handler

javascript
document.addEventListener('keydown', (event) => {
  const key = event.key;

  if (/^[0-9]$/.test(key)) {
    handleAction('digit', key);
    return;
  }

  if (key === '.') {
    handleAction('decimal');
    return;
  }

  const operations = {
    '+': '+',
    '-': '-',
    '*': '*',
    '/': '/'
  };

  if (operations[key]) {
    handleAction('operation', operations[key]);
    return;
  }

  if (key === 'Enter' || key === '=') {
    event.preventDefault();
    handleAction('equals');
    return;
  }

  if (key === 'Backspace') {
    handleAction('backspace');
    return;
  }

  if (key === 'Escape') {
    handleAction('clear');
  }
});

The keyboard handler does not perform calculations. It only translates keys into the same actions used by the buttons.

Test

Without clicking the calculator:

  1. Type 12.
  2. Press +.
  3. Type 8.
  4. Press Enter.

The display should show 20.

Also test:

  • *
  • /
  • -
  • .
  • Backspace
  • Escape

Checkpoint

Mouse and keyboard input now use the same calculator behavior.