Detect Key Press in JavaScript

Detecting key press in javascript can be a very useful feature as it enhances user’s interaction with the web applications. This article explains how can you do it:

Keydown Event

The keydown event is triggered when user presses down a key. For example:
 // Detect key press using keydown event 
document.addEventListener('keydown', function(event) { console.log('Key pressed: ' + event.key); }); 
In this code, the keydown event listener is added. When a key is pressed, it pritns the rpessed key in the browser console.

Detecting Specific Key Press

You can also detect the keys pressed by the users by checking the value of event.key. For example, to detect when the “Enter” key is pressed:
  
document.addEventListener('keydown', function(event) { if (event.key === 'Enter') { console.log('Enter key was pressed.'); } }); 
This will only trigger when the “Enter” key is pressed, and the same method can be used to detect other keys such as “Esc”, “Arrow keys”, etc.

Keyup and Keypress Events

In addition to keydown, there are two other key-related events: keyup: This event is triggered when the key is released by the user. keypress: This event is triggered when the key is pressed down (however this event is now deprecated in modern browsers, so it is recommended to use keydown event instead). Here’s an example of detecting a key release:
 // Detect key release using keyup event document.addEventListener('keyup', function(event) { console.log('Key released: ' + event.key); }); 
This will log the key that was released.

Leave a Comment