js keyboard event listener code example

Example 1: javascript keyboard events

document.addEventListener("keydown", function(event) {
  if (event.keyCode == 32) {
    console.log("Space was pressed!");
  }
});

Example 2: keyboard event js

document.addEventListener("keydown", function(event) {
  console.log(`Key pressed: ${event.key}`);
  // event.key is a string representing which key has been pressed
});

Example 3: keydown events

eventTarget.addEventListener("keydown", event => {
  if (event.isComposing || event.keyCode === 229) {
    return;
  }
  // do something
});