Detecting Keyboard Pressed Key and Code using JavaScript Tutorial

In this tutorial, you can learn how to Detect the Pressed Key and Code of the Keyboard using JavaScript. The tutorial aims to provide students and new programmers with a reference for learning some useful techniques that might help them to achieve the requirements of their current or future projects. Here, I will be providing simple web page scripts that demonstrate the main goal of this tutorial.

Why do we need to detect the pressed key in a web application?

Detecting the pressed key on the keyboard is not required in building a website or web application. Developers often implement this kind of feature to give their clients or end-users a better experience while using their developed apps. Detecting the pressed keys can help you identify the keys code which is commonly used by developers to execute another functionality when the specific key has been pressed or hit.

How to Detect the Pressed Key and Code of the Keyboard using JavaScript?

Detecting the Pressed Key and Code of the keyboard is not complicated to achieve. JavaScript comes with built-in methods, event listeners, and APIs and some of these became handy for detecting the pressed key data. Using the keypress, keyup, and keydown event listeners of JS we can simply detect that there is a key has been pressed and using the event data or object we can identify the key character or code of the key has been pressed. Check out the simple web page script that I created and provided below to understand it more.

Sample Web Page

The scripts below result in a simple web page that can detect the pressed key and code and display the pressed key details on a block or panel of the page.

HTML

Here's the HTML file script known as index.html. This file contains the HTML elements that will be used for the page layout or interface of the page.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>HTML CSS and JS - Detecting Key Pressed</title>
  7.     <link rel="preconnect" href="https://fonts.googleapis.com">
  8.     <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9.     <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
  10.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  11.     <link rel="stylesheet" href="style.css">
  12.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  13. </head>
  14.     <div class="content-md-lg py-3">
  15.         <div class="col-lg-8 col-md-10 col-sm-12 col-12 mx-auto">
  16.             <div class="page-title">Detecting Key Pressed using HTML, CSS, and JavaScript</div>
  17.             <hr style="margin:auto; width:25px" class="border-light opacity-100">
  18.         </div>
  19.         <div class="container-lg">
  20.             <div class="row py-3 my-2">
  21.                 <div class="col-lg-5 col-md-5 col-sm-10 col-12 mx-auto">
  22.                     <div class="card rounded-0">
  23.                         <div class="card-body">
  24.                             <div class="container-fluid">
  25.                                 <div id="bigDetails">
  26.                                     <div class="keyPressed">-</div>
  27.                                     <div class="keyCodePressed">-</div>
  28.                                 </div>
  29.  
  30.                                 <div id="smallDetails">
  31.                                     <label for="keyPressedLabel">Pressed Key</label>
  32.                                     <div class="keyPressed">-</div>
  33.                                     <label for="keyCodePressedLabel">Pressed Key Code</label>
  34.                                     <div class="keyCodePressed">-</div>
  35.                                 </div>
  36.                             </div>
  37.                         </div>
  38.                     </div>
  39.                 </div>
  40.             </div>
  41.         </div>
  42.     </div>
  43.     <script src="script.js"></script>
  44. </body>
  45. </html>

CSS

Next, here is the CSS file script known as style.css. This file contains the custom stylesheet script for some of the page interfaces and designs.

  1. @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@200&family=Space+Mono&display=swap" rel="stylesheet');
  2. @import url('https://fonts.googleapis.com/css2?family=Tillana:wght@400;600&display=swap');
  3. :root{
  4.     --space-mono-font: 'Space Mono', monospace;
  5.     --border-dark-subtle: #373838;
  6.     --font-tillana:'Tillana', cursive;
  7. }
  8. *{
  9.     box-sizing: border-box;
  10. }
  11. body *{
  12.     font-family: var(--space-mono-font);
  13. }
  14. /**
  15. Page Design
  16. */
  17. body,
  18. html{
  19.     height: 100%;
  20.     width: 100%;
  21.     margin: 0;
  22.     padding: 0;
  23. }
  24. body{
  25.     background-color: #282A3A;
  26. }
  27. .page-title{
  28.     font-size: 2.5rem;
  29.     font-weight: 500;
  30.     color: #fff;
  31.     letter-spacing: 3px;
  32.     font-family: var(--secular-font);
  33.     text-align: center;
  34.     text-shadow: 0px 0px 3px #2020208c;
  35. }
  36. .border-dark-subtle{
  37.     border-color: var(--border-dark-subtle) !important;
  38. }
  39.  
  40. /* div#bigDetails {
  41.     display: flex;
  42.     align-items: center;
  43.     justify-content: center;
  44.     width: 100%;
  45. } */
  46. div#bigDetails .keyPressed {
  47.     color: #14b8c9;
  48.     font-size: 1.8rem;
  49.     padding: 0 1.2em;
  50.     font-weight: 600;
  51.     text-align: center;
  52. }
  53. div#bigDetails .keyCodePressed {
  54.     color: #14b8c9;
  55.     font-size: 2rem;
  56.     padding: 0 1.2em;
  57.     font-weight: 600;
  58.     text-align: center;
  59. }
  60.  
  61. #smallDetails{
  62.     margin-top: 2em;
  63.     text-align: center;
  64. }
  65. #smallDetails label{
  66.     color: #757575;
  67. }
  68. #smallDetails div{
  69.     color: #000;
  70.     font-weight: 500;
  71. }
  72.    

JavaScript

Finally, here is the JS file script known as script.js. This file contains the codes that detect the pressed key on the web page and display the details on their designated text field.

  1. // Element Selector
  2. const keyPressedField = document.querySelectorAll('.keyPressed')
  3. const keyCodePressedField = document.querySelectorAll('.keyCodePressed')
  4.  
  5. document.body.addEventListener('keyup', e => {
  6.     // Getting the press keyboard key
  7.     var pressedKey = e.code || e.key
  8.     // Getting the press keyboard key code or Character Code
  9.     var pressedKeyCode = e.charCode || e.keyCode || e.which
  10.  
  11.     keyPressedField.forEach(el => {
  12.         // Update the Pressed Key Text Fields
  13.         el.innerText = pressedKey
  14.     })
  15.  
  16.     keyCodePressedField.forEach(el => {
  17.         // Update the Pressed Key Code Text Fields
  18.         el.innerText = pressedKeyCode
  19.     })
  20. })

Snapshots

Here are some snapshots of the overall result of the scripts I have provided above.

Web Page UI

Detecting Pressed Key using JavaScript

Sample Pressed Key Result #1

Detecting Pressed Key using JavaScript

Sample Pressed Key Result #2

Detecting Pressed Key using JavaScript

Sample Pressed Key Result #3

Detecting Pressed Key using JavaScript

DEMO

Detecting Pressed Key using JavaScript

There you go! I have provided also the complete source code zip file of the scripts I provided above on this website. The source code zip file is free to download on this site. Feel free to download and do some experiments to enhance your JS programming capabilities and knowledge.

That's it! I hope this Detecting Keyboard Pressed Key and Code using JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment