Keyboard Events in JavaScript
Handle keyboard events in JavaScript with keydown and keyup, e.key and e.code, modifier keys, preventDefault and a shortcut map. Clear explanation and output.
This code needs a web page. Add the HTML elements it looks up by id, link the script, and open the page in a browser. Node has no document object. Add <input id="myInput"> and click the page before typing.
1// Method 1: Keydown event2document.addEventListener('keydown', function(e) {3 console.log('Key pressed:', e.key);4 console.log('Key code:', e.keyCode);5 console.log('Code:', e.code);6});78// Method 2: Keyup event9document.addEventListener('keyup', function(e) {10 console.log('Key released:', e.key);11});1213// Method 3: Keypress event (deprecated, use keydown)14document.addEventListener('keypress', function(e) {15 console.log('Character:', e.key);16});1718// Method 4: Specific keys19document.addEventListener('keydown', function(e) {20 if (e.key === 'Enter') {21 console.log('Enter pressed');22 } else if (e.key === 'Escape') {23 console.log('Escape pressed');24 } else if (e.key === 'ArrowUp') {25 console.log('Arrow up');26 }27});2829// Method 5: Modifier keys30document.addEventListener('keydown', function(e) {31 if (e.ctrlKey && e.key === 's') {32 e.preventDefault();33 console.log('Ctrl+S pressed - Save');34 }3536 if (e.shiftKey && e.key === 'Enter') {37 console.log('Shift+Enter');38 }3940 if (e.altKey && e.key === 'f') {41 console.log('Alt+F');42 }4344 if (e.metaKey && e.key === 'k') {45 console.log('Cmd+K (Mac) or Ctrl+K');46 }47});4849// Method 6: Input field keyboard events50const input = document.getElementById('myInput');5152input.addEventListener('keydown', function(e) {53 if (e.key === 'Enter') {54 console.log('Form submitted');55 }56});5758input.addEventListener('keyup', function(e) {59 console.log('Input value:', e.target.value);60});6162// Method 7: Prevent default for specific keys63document.addEventListener('keydown', function(e) {64 // Prevent spacebar from scrolling65 if (e.key === ' ' && e.target.tagName !== 'INPUT') {66 e.preventDefault();67 }6869 // Prevent F5 refresh70 if (e.key === 'F5') {71 e.preventDefault();72 }73});7475// Method 8: Keyboard shortcuts76const shortcuts = {77 'ctrl+k': () => console.log('Search'),78 'ctrl+s': () => console.log('Save'),79 'ctrl+z': () => console.log('Undo'),80 'ctrl+shift+z': () => console.log('Redo')81};8283document.addEventListener('keydown', function(e) {84 const key = e.key.toLowerCase();85 let shortcut = '';8687 if (e.ctrlKey) shortcut += 'ctrl+';88 if (e.shiftKey) shortcut += 'shift+';89 if (e.altKey) shortcut += 'alt+';9091 shortcut += key;9293 if (shortcuts[shortcut]) {94 e.preventDefault();95 shortcuts[shortcut]();96 }97});
Sample Output
Character: a
keypress still fires in most browsers but is deprecated.
Save
The shortcut map matched "ctrl+s" and ran its function.
In this one
- The difference between keydown, keyup and keypress
- How key, code and keyCode differ
- How to detect Ctrl, Shift, Alt and Meta
- How to build a keyboard shortcut map
How it works
- 1
A keydown listener logs key, keyCode and code.
- 2
keyup logs the released key.
- 3
Specific keys like Enter and Escape are checked.
- 4
Modifier combos like Ctrl+S are caught and default prevented.
- 5
Input events read the field value.
- 6
A shortcut string is built and matched against the shortcuts object.
Edge cases
Shift changes key
With Shift held, e.key is "S", not "s".
The shortcut map lowercases the key first.
Browser-reserved shortcuts
Ctrl+W or Ctrl+T may close or open tabs before your code runs.
Some combos cannot be blocked. Choose shortcuts the browser does not reserve.
Key held down
keydown fires again and again while held.
Check e.repeat to ignore auto-repeat.
What's going on
Keyboard events let your page react to keys. Typing in a search box, pressing Enter to send a chat message, or using arrow keys in a quiz game all use them.
There are three event types. keydown fires when a key is pressed down. keyup fires when it is released. keypress fires when a character is typed, but it is deprecated. Deprecated means it is old and may be removed, so use keydown instead.
The event object has a few key properties. key is the character or key name, like "a", "Enter" or "ArrowUp". code is the physical key on the keyboard, like "KeyA". keyCode is an old numeric code and is also deprecated. Prefer key in new code.
Method 4 checks common keys: Enter, Escape and the arrow keys. Others you will meet are Space, Tab, Backspace and the function keys F1 to F12.
Method 5 checks modifier keys. These are keys you hold with another key. ctrlKey, shiftKey, altKey and metaKey are true while Ctrl, Shift, Alt or Cmd (on Mac) are held. Ctrl+S normally saves the web page, so the code calls preventDefault() to stop that and run its own save.
Method 6 listens on an input. Enter acts like submit, and keyup reads the current value.
Method 7 prevents defaults on purpose. Space would scroll the page, so it is blocked unless you are typing in an input. F5 refresh is blocked too, though use this with care.
Method 8 builds a shortcut string like "ctrl+shift+z" and looks it up in an object. It is a tidy way to manage many shortcuts.
Use cases include shortcuts, form validation, game controls, and accessibility. Best practices: use key instead of keyCode, check modifier keys, and prevent default only when needed.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which event should replace keypress?
Pick an answer to check it.
Question 2
Which property is true while Ctrl is held?
Pick an answer to check it.
Questions people ask
Should I use key or code?
Use key for the character typed. Use code when the physical position matters, like WASD in games.
Why is keyCode still shown?
Old code uses it. It is deprecated, so avoid it in new work.
Is blocking F5 a good idea?
Rarely. Users expect refresh to work. It is shown only as an example.