JAVASCRIPT

How to handle keyboard events?

keyboard events

Keyboard events in JavaScript let you detect when a user presses, holds, or releases a key. These are commonly used for things like shortcuts, form handling, and navigation.

๐Ÿ”‘ Types of Keyboard Events

  1. keydown โ€“ Fires when a key is pressed down (fires repeatedly if the key is held).
  2. keypress โ€“ (deprecated) โ€“ Was used for character-producing keys only. Avoid using this.
  3. keyup โ€“ Fires when a key is released.

โœจ Example: Basic Key Handling

document.addEventListener("keydown", function(event) {
  console.log("Key down:", event.key);   // e.g., "a", "Enter"
});

document.addEventListener("keyup", function(event) {
  console.log("Key up:", event.key);
});

๐ŸŽฏ Useful event Properties

  • event.key โ†’ The character value (e.g., "a", "Enter", "ArrowUp").
  • event.code โ†’ The physical key on the keyboard (e.g., "KeyA", "ArrowLeft").
  • event.altKey / event.ctrlKey / event.shiftKey / event.metaKey โ†’ Boolean values indicating if modifier keys were pressed.
document.addEventListener("keydown", function(event) {
  if (event.ctrlKey && event.key === "s") {
    event.preventDefault();  // stop browserโ€™s Save dialog
    console.log("Ctrl + S shortcut detected!");
  }
});

โŒจ๏ธ Example: Arrow Key Navigation

document.addEventListener("keydown", function(event) {
  switch(event.key) {
    case "ArrowUp":
      console.log("Move up");
      break;
    case "ArrowDown":
      console.log("Move down");
      break;
    case "ArrowLeft":
      console.log("Move left");
      break;
    case "ArrowRight":
      console.log("Move right");
      break;
  }
});

โš ๏ธ Best Practices

  • Use event.key for readable key names (instead of old keyCode).
  • Always use preventDefault() if you donโ€™t want the browserโ€™s default action (like space scrolling).
  • Use event delegation if handling keys inside a specific input/area.
  • Be mindful of accessibility โ€“ donโ€™t block standard navigation keys unnecessarily.
No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *