Back to JavaScript Notes
Topic #149

Keyboard Events

Keyboard events capture key presses for shortcuts, games and form control. They enable power-user interactions.

Keyboard Events happen when the user presses a key on the keyboard:

  • keydown (key is pressed down)
  • keyup (key is released)
  • keypress (deprecated)

Note: keypress only fires for character keys (a or 5), not for control keys (alt or backspace). Developers are advised to use keydown or keyup instead.


The keydown Event

Using event.key

Example

<input id="k" type="text" placeholder="Press a key">

<p id="demo"></p>

<script>

const k = document.getElementById("k");

// Let k listen for keydown

k.addEventListener("keydown", function (event) {

// Then display the event.key

  document.getElementById("demo").innerHTML = "You pressed: " + event.key;

});

</script>

Key Properties

The KeyboardEvent object provides useful properties to determine which key was involved in the event:

Col 1 Col 2 Col 3
Property Description When pressing Z
event.key Returns the value of the key. Can vary based on language settings. Returns z (or Z if shift is held)
event.code Returns the key code. Constant, regardless of language settings. Always returns "KeyZ"

Note: You can also detect modifier keys using properties like event.ctrlKey, event.shiftKey, event.altKey, and event.metaKey to implement key combinations (e.g., Ctrl + S).


Detect Enter Using event.code

Summary JavaScript provides keyboard events to detect and handle user input from the keyboard,

enabling interactive web experiences like form validation, game controls, and keyboard shortcuts.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Keyboard Events – FAQs

Quick answers about learning Keyboard Events in JavaScript.

This free note from Coding Now Tech Institute explains Keyboard Events in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including Keyboard Events, is 100% free with no signup required.
With focused practice, most students grasp Keyboard Events in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now