Telegram Group Join Now
Detect Key Pressed – Javascript onkeypress keycode
Hey friends, today we will see how to make this cool fun project. Let’s see how it works.
When the page is displayed, an interface like the below appears:
HTML & JS CODES
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Detect Pressed Key in JavaScript</title>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="box">
<p class="text">Press any key</p>
<div class="content">
<div class="key-code"></div>
<div class="key-name"></div>
<div class="details">
<p class="key">Key: <span></span></p>
<p class="code">Code: <span></span></p>
</div>
</div>
</div>
<script>
const box = document.querySelector(".box");
document.addEventListener("keydown", e =>{
let keyName = e.keyCode === 32 ? "Space" : e.key;
box.querySelector(".key-code").innerText = e.keyCode;
box.querySelector(".key-name").innerText = keyName.toUpperCase();
box.querySelector(".key span").innerText = keyName;
box.querySelector(".code span").innerText = e.keyCode;
box.classList.add("active");
});
</script>
</body>
</html>
</body>
</html>
The output would be:
CSS Codes
/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
display: flex;
min-height: 100vh;
align-items: center;
justify-content: center;
background: gold;
}
.box{
padding: 25px;
width: 290px;
border-radius: 15px;
background: #fff;
box-shadow: 7px 7px 20px rgba(0, 0, 0, 0.05);
}
.text, .key-code, .key-name{
font-size: 45px;
color: gold;
font-weight: 500;
}
.text{
font-size: 30px;
text-align: center;
pointer-events: none;
}
.box.active .text{
display: none;
}
.content, .key-code, .details{
display: flex;
align-items: center;
justify-content: center;
}
.content{
display: none;
flex-direction: column;
}
.box.active .content{
display: flex;
}
.content .key-code{
height: 110px;
width: 110px;
background: #fff;
border-radius: 50%;
margin-bottom: 15px;
pointer-events: none;
border: 5px solid #17A2B8;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.content .details{
width: 100%;
margin-top: 15px;
justify-content: space-evenly;
}
.details p{
width: 100%;
font-size: 18px;
text-align: center;
}
.details p:last-child{
border-left: 1px solid #bfbfbf;
}
And that’s all for this project. Thanks for reading and goodbye!
Written by: @codingporium