DEV Community

Ahtsham Ajus
Ahtsham Ajus

Posted on

Today I Learned to creat a Event Key Codes

We now know how to handle different types of input from the mouse, but let's not forget about the keyboard. We can handle input from the keyboard similiarly to how we handled input from the mouse. We use special event methods that take a callback function!

For example, the code returned is "KeyQ" for the Q key on a QWERTY layout keyboard, but the same code value also represents the ' key on Dvorak keyboards and the A key on AZERTY keyboards. That makes it impossible to use the value of code to determine what the name of the key is to users if they're not using an anticipated keyboard layout.

Here's HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Event KeyCodes</title>
</head>
<body>
  <div id="insert">
        <div class="key">
            Press any key to get the keyCode
        </div>
  </div>   

    <script src="./script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Here's My CSS code



@import url('https://fonts.googleapis.com/css?family=Ubuntu&display=swap');


*{
    box-sizing: border-box;
}

body {
    background-color: #e1e1e1;
    font-family:'Ubuntu', sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    overflow: hidden;
    height: 100vh;
    margin: 0;
}

.key {
    border: 1px solid #999;
    background-color: #eee;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
    display: inline-flex;
    align-items: center;
    font-size: 20px;
    font-weight: bold;
    padding: 20px;
    flex-direction: column;
    margin: 10px;
    min-width: 150px;
    position: relative;
}

.key small {
    position: absolute;
    top: -24px;
    left: 0;
    text-align: center;
    width: 100%;
    color: #555;
    font-size: 14px;
}
Enter fullscreen mode Exit fullscreen mode

Here's My JavaScript code

const insert = document.getElementById('insert')

window.addEventListener('keydown', (event) => {
   insert.innerHTML = `
   <div class="key">
   ${event.key === ' ' ? 'Space' : event.key}
   <small>event.key</small>
</div>

<div class="key">
   ${event.keyCode}
   <small>event.keyCode</small>
</div>

<div class="key">
   ${event.code}
   <small>event. code</small>
 </div>`
})
Enter fullscreen mode Exit fullscreen mode

Here's a ouput

Top comments (0)