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 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:

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/


→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list