javascript
  1. javascript-keypress

JavaScript Keypress

JavaScript keypress event occurs when a key on the keyboard is pressed down. It is commonly used to implement keyboard shortcuts and capture user input.

Syntax

element.addEventListener("keypress", function(event) {
  // Code to handle the event
});

Example

<input type="text" id="myInput">

<script>
  var input = document.getElementById("myInput");
  input.addEventListener("keypress", function(event) {
    console.log("Key pressed: " + event.key);
  });
</script>

Output

When a key is pressed in the input field, the key value is logged on the console.

Explanation

In the above example, we first retrieve a reference to the input field by using the getElementById method. Then we attach a keypress event listener to the input field using the addEventListener method.

Inside the event handler function, we simply log the key property of the event object to the console.

Use

The keypress event is useful for capturing user input and implementing keyboard shortcuts. For example, you can use it to validate user input in a form, or to implement custom navigation in a web application.

Important Points

  • The keypress event only fires when a printable key is pressed. Non-printable keys like Shift, Ctrl, and Alt do not trigger the event.
  • The event object has several properties that provide information about the key that was pressed, including key, keyCode, and charCode.
  • The keypress event is not supported in mobile browsers. Use the keydown or keyup events instead.

Summary

  • The keypress event fires when a printable key is pressed.
  • It is commonly used to capture user input and implement keyboard shortcuts.
  • Non-printable keys like Shift, Ctrl, and Alt do not trigger the event.
  • The event object provides information about the key that was pressed.
  • Use the keydown or keyup events instead for mobile browsers.
Published on: