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
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:
- Type
12. - Press
+. - Type
8. - Press
Enter.
The display should show 20.
Also test:
*/-.BackspaceEscape
Checkpoint
Mouse and keyboard input now use the same calculator behavior.