Mastering Keyboard Events in JavaScript: A Comprehensive Guide


Keyboard events in JavaScript are events that are triggered when a user interacts with the keyboard, such as pressing a key, releasing a key, or typing a key. These events allow web developers to capture and respond to user input from the keyboard in web applications.

There are three main types of keyboard events in JavaScript:

  • keydown event: This event is triggered when a key is initially pressed down on the keyboard. It occurs when the physical key is first pressed down, and it may be triggered repeatedly if the key is held down.
  • keyup event: This event is triggered when a key is released after being pressed down on the keyboard. It occurs when the physical key is released, and it is only triggered once when the key is released.
  • keypress event: This event is triggered when a key that represents a character value is actually typed by the user. It occurs after the keydown event and before the keyup event, and it is typically used to capture character input, such as in text fields or other input elements.
  • key property: The key property of the event object represents the physical key that was pressed or released during a keyboard event.
  • code property: The code property of the event object represents the physical key that was pressed or released during a keyboard event, as a standardized string value that does not depend on the keyboard layout or locale.

To handle keyboard events in JavaScript, event listeners can be attached to the target element using the DOM (Document Object Model) manipulation methods. The event listeners are functions that are executed when a keyboard event is triggered on the specified element.

Keydown

The keydown event is a keyboard event that is triggered when a key is initially pressed down by the user. It is commonly used in JavaScript to capture and handle user input from the keyboard. The keydown event is fired when the physical key is pressed down, regardless of whether the key is subsequently held down or released.

Here's an example of how to handle the "Keydown" event using JavaScript:

 <label for="input-num">Enter a Number</label>
 <input type="text" id="input-num" />

/*document.addEventListener("keydown", handleKeyEvent);

function handleKeyEvent(event) {
  const eventType = event.type;
  console.log(`Event type: ${eventType}`);
}
*/

const input = document.getElementById("input-num");
const msg = document.getElementById("error");

input.addEventListener("keydown", function (event) {
  const key = event.key;
  console.log(key);
  if (isNaN(key)) {
    event.preventDefault();
    msg.textContent = "Please Enter Number only";
  } else {
    msg.textContent = "";
  }
});

The code snippet provided demonstrates how to handle the keydown event in JavaScript to validate user input in an input field with an ID of "input-num" and display an error message in an element with an ID of "error" if the input is not a number.

Here's a breakdown of the code:

  1. The keydown event is attached to the document object with an event listener function handleKeyEvent using the addEventListener method. This function will be executed whenever a key is pressed down on the keyboard.
  2. The handleKeyEvent function logs the type of the event (keydown) to the console.
  3. The input element with an ID of "input-num" is selected using document.getElementById and an event listener function is attached to it using addEventListener method.
  4. The event listener function for the keydown event on the input element takes an event parameter, which represents the event object that contains information about the keydown event, such as the key that was pressed (event.key).
  5. The key property of the event object is retrieved and logged to the console. This property represents the value of the key that was pressed, such as a letter, number, or symbol.
  6. The isNaN function is used to check if the key value is not a number. If it is not a number, event.preventDefault() is called to prevent the input from accepting non-numeric characters.
  7. If the key value is not a number, an error message is displayed in the element with an ID of "error" using the textContent property. Otherwise, the error message is cleared by setting the textContent property to an empty string.

This code can be used to ensure that only numeric input is accepted in the "input-num" field and display an error message if any non-numeric characters are entered. Note that the keydown event is used in this example, which triggers when a key is initially pressed down, but it may not capture certain non-character keys (such as arrow keys, function keys, etc.). Depending on your use case, you may need to consider using other keyboard events such as keypress or input for more robust input validation.

It's important to be mindful of accessibility considerations when using keydown event listeners, as some keys may have special functions or mappings in certain assistive technologies or input methods. Also, keep in mind that different browsers may have slightly different behavior and support for certain keys or key combinations, so it's recommended to test and verify the behavior across different browsers and devices when using the keydown event in your web applications.

keypress (deprecated)

The keypress event is a keyboard event that is triggered when a key is initially pressed down and a character is generated by the key, typically resulting in a printable character being displayed on the screen. It is commonly used in JavaScript to capture and handle user input from the keyboard when printable characters are typed, such as letters, numbers, and symbols.

Here's an example of how to handle the "keypress" event using JavaScript:

 <label for="input-num">Enter a Number</label>
 <input type="text" id="input-num" />
const input = document.getElementById("input-num");
const msg = document.getElementById("error");

input.addEventListener("keypress", function (event) {
  const key = event.key;
  console.log(key);
  if (isNaN(key)) {
    event.preventDefault();
    msg.textContent = "Please Enter Number only";
  } else {
    msg.textContent = "";
  }
});

Please note that the keypress event is being deprecated in favor of the input event in modern web standards, as it provides more consistent and reliable input handling across different devices and input methods. However, the keypress event may still be used in older or legacy web applications, or in specific use cases where printable character input is required.

keyup

The keyup event in JavaScript is triggered when a key is released after being pressed down on the keyboard. It is one of the keyboard events that can be used to detect when a specific key is released by the user.

Here's an example of how to handle the "keyup" event using JavaScript:

 <label for="input-num">Enter a Number</label>
 <input type="text" id="input-num" />
document.addEventListener("keyup", handleKeyEvent);

function handleKeyEvent(event) {
  const eventType = event.type;
  console.log(`Event type: ${eventType}`);
}

key

In JavaScript, the key property is a property of the event object that represents the value of the key that was pressed or released during a keyboard event. It provides information about the specific key that triggered the event, such as a letter, number, or special character.

The key property returns a string that represents the value of the key in a human-readable format, regardless of whether the key is uppercase or lowercase.

The key property is commonly used in keyboard event handlers to determine which key was pressed or released, and to perform different actions based on the value of the key.

Here's an example of how to handle the "key" property using JavaScript:

 <label for="input-num">Enter a Number</label>
 <input type="text" id="input-num" />
document.addEventListener("keyup", handleKeyEvent);

function handleKeyEvent(event) {
  const keyName = event.key;
  console.log(`Key name: ${keyName}`);
}

code

The "code" property may refer to a custom property that has been added to a DOM element by a developer using their own JavaScript code. In JavaScript, it's possible to add custom properties to DOM elements or any other JavaScript objects by simply assigning a value to a property that doesn't already exist on the object.

Here's an example of how to handle the "code" event using JavaScript:

 <label for="input-num">Enter a Number</label>
 <input type="text" id="input-num" />
document.addEventListener("keyup", handleKeyEvent);

function handleKeyEvent(event) {
  const keyCode = event.code;
  console.log(`Key code: ${keyCode}`);
}

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1>Keyboard Event in JavaScript</h1>
    <p>Press Any Key</p>
    <hr />
    <label for="input-num">Enter a Number</label>
    <input type="text" id="input-num" />
    <p id="error"></p>

    <script src="113_event2.js"></script>
  </body>
</html>

script.js

/*
  2.Keyboard
    Keydown
    keypress (deprecated)
    keyup
    key
    code
  */

document.addEventListener("keydown", handleKeyEvent);
document.addEventListener("keypress", handleKeyEvent);
document.addEventListener("keyup", handleKeyEvent);

function handleKeyEvent(event) {
  const eventType = event.type;
  const keyCode = event.code;
  const keyName = event.key;
  console.log(`Event type: ${eventType}`);
  console.log(`Key code: ${keyCode}`);
  console.log(`Key name: ${keyName}`);
}

//-----------------------------------------------------------

const input = document.getElementById("input-num");
const msg = document.getElementById("error");

input.addEventListener("keydown", function (event) {
  const key = event.key;
  console.log(key);
  if (isNaN(key)) {
    event.preventDefault();
    msg.textContent = "Please Enter Number only";
  } else {
    msg.textContent = "";
  }
});

//-----------------------------------------------------------

List of Programs


JS Practical Questions & Answers


JS Practical Project