Skip to content

Keyboard events

Discover the basics of working with keyboard events in JavaScript

There are 3 types of events when interacting with keyboard events:

  • keydown the keyboard key has been pressed
  • keyup the keyboard key has been released

keydown is also fired when the key repeats while the button stays pressed.

While mouse and touch events are typically listened on a specific element, it's common to listen for keyboard events on the document:

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

The parameter passed to the event listener is a KeyboardEvent.

This event object, in addition to the Event object properties offers us (among others) these unique properties:

  • altKey true if alt key was pressed when the event was fired
  • code the code of the key pressed, returned as a string
  • ctrlKey true if ctrl key was pressed when the event was fired
  • key the value of the key pressed, returned as a string
  • locale the keyboard locale value
  • location the location of the key on the keyboard
  • metaKey true if meta key was pressed when the event was fired
  • repeat true if the key has been repeated (e.g. the key has not been released)
  • shiftKey true if shift key was pressed when the event was fired

This demo is a keylogger which will show you the values of some of the properties I listed above: https://codepen.io/flaviocopes/pen/LopWmq/

→ Download my free JavaScript Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about browser: