Detect Keyboard key press using JavaScript

1 min read

We are going to use JavaScript to detect which key is pressed in keyboard. We will track an event listener to know the key code and key name of the key that is being pressed and show it in webpage.


Source Code :

<style type="text/css">
    background: chocolate;
    height: 100vh;
    position: relative;
    overflow: hidden;
    padding: 30px;
    width: 400px;
    background: #fff;
    border-radius: 15px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    border: 4px solid teal;
    padding: 20px 0px;
    font-size: 2em;
    text-align: center;
    text-transform: uppercase;
    border-bottom: 4px solid teal;
    padding: 20px 0px;
    font-size: 3em;
    letter-spacing: 2px;
    text-align: center;
    display: none;
    font-size: 28px;
    background: teal;
    color: #fff;
    text-align: center;
    border-radius: 10px;
    padding: 10px;

<div class="box-wrapper">
  <div class="box">
    <div class="key-btn">Press a Key</div>
    <div class="key-name">
    <div class="key-code">
      Code : 32

<script type="text/javascript">
  btn = document.getElementsByClassName('key-btn')[0];
  keyname = document.getElementsByClassName('key-name')[0];
  keycode = document.getElementsByClassName('key-code')[0];

  document.addEventListener("keydown", e=>{
      name = 'space';
      name = e.key;
    } = 'none';
    keyname.innerHTML = name;
    keycode.innerHTML = 'Code : '+e.keyCode; = 'block'; = 'block';


Recommended For You

About the Author: Ritesh Ghimire