Keyboard events

Explore the basics of handling keyboard events in JavaScript

When interacting with keyboard events, there are 3 types of events:

  • keydownKeyboard key has been pressed
  • keyupKeyboard key has been released

keydownIt also triggers when the key is repeatedStayPress down.

Although mouse and touch events are usually monitored on specific elements, keyboard events are usually monitored on the keyboard.Documentation:

document.addEventListener('keydown', event => {
  // key pressed
})

The parameters passed to the event listener areKeyboardEvent.

apart fromEvent object propertiesProvide us (among other things) with these unique attributes:

  • altKeyTrue if the alt key was pressed when the event was triggered
  • codeThe code of the pressed key, returned as a string
  • ctrlKeyTrue if the ctrl key is pressed when the event is triggered
  • keyThe value of the pressed key, returned as a string
  • localeKeyboard locale value
  • locationThisLocation of the keyOn the keyboard
  • metaKeyReturns true if the meta key is pressed when the event is triggered
  • repeatTrue if the key has been duplicated (for example, the key has not been released)
  • shiftKeyTrue if the Shift key was pressed when the event was triggered

The demo is a keylogger that will show you the values of some of the properties I listed above:

Look at the penKeylogger demoBy Flavio Copes (@flaviocopes) InCipher pen.

Tech Wiki Online!