Key Press Detector

This code listens for any key pressed on the keyboard using the keydown event listener attached to the document. When a key is pressed, JavaScript automatically provides an event object that contains information about the key, including which key was pressed. The code accesses event.key to get the key value and then updates the text inside the heading element using innerText to display the pressed key on the screen.

<!DOCTYPE html>
<html>
<body>

  <!-- Heading to show pressed key -->
  <h2 id="output">Press any key</h2>

  <!-- Link JavaScript -->
  <script src="key.js"></script>

</body>
</html>

// Add event listener for key press
document.addEventListener("keydown", function(event) {

  // Display the key pressed by the user
  document.getElementById("output").innerText =
    "You pressed: " + event.key;

});

Leave a Reply

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