keyboard events in javascript code example

Example 1: js keyboard input

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        alert('Left was pressed');
    }
    else if(event.keyCode == 39) {
        alert('Right was pressed');
    }
});

Example 2: javascript keyboard events

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

Example 3: 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
});