Test Display Key (Code) Typed

In this example below you will see how to do a Test Display Key (Code) Typed with some HTML / CSS and Javascript

This awesome code was written by FarhanSharif, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright FarhanSharif ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

  <meta charset="UTF-8">
  <title>Test Display Key (Code) Typed</title>


  <input type="text" id="box"></input>
<div id="typed"></div>

    <script  src="js/index.js"></script>



/*Downloaded from https://www.codeseek.co/FarhanSharif/test-display-key-code-typed-qYrwEE */

// When document has loaded, wait for text box to be focused, then listen for keys
document.addEventListener("DOMContentLoaded", function() {
  // When text box focused, listen for keys pressed
  document.getElementById("box").addEventListener("focus", function() {
    this.addEventListener("keydown", listenForKeys);
  // When text box loses focus, remove key listener so that it is not added again when box is focused again
  document.getElementById("box").addEventListener("blur", function() {
    document.getElementById("box").removeEventListener("keydown", listenForKeys);

function listenForKeys(keypress) {
      // Prevents default behavious (such as tab and alt) which makes box lose focus
      // This also stops keys from being entered into the box! (That functionality was desired here)
      // Print out key name "c", "Control", etc. and the corresponding keyCode 
      document.getElementById("typed").innerText = "Key: " + keypress.key + 
                                                   "\nKey Code: " + keypress.keyCode +
                                                   "\nLocation: " + keypress.location;