Explain Key-events in JavaScript?


The key-events happen whenever a user interacts with keyboard. There are mainly three key event types − keydown, keypress and keyup.

EventDescription
OnkeydownThis event fires when the user is pressing a key
OnkeypressThis event fires when the user presses the key
OnkeyupThis event fires when the user releases the key.

Following is the code for key events in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      color: blueviolet;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Key-events in JavaScript</h1>
<div class="result"></div>
<h3>Press or release key to see the keyevent fired</h3>
<script>
   let resEle = document.querySelector(".result");
   document.body.addEventListener("keydown", () => {
      resEle.innerHTML = "keydown event is being fired <br>";
   });
   document.body.addEventListener("keyup", () => {
      resEle.innerHTML = "keyup event is being fired";
   });
   document.body.addEventListener("keypress", () => {
      resEle.innerHTML += "keypress event is being fired";
   });
</script>
</body>
</html>

Output

On holding down the key −

On releasing the key −


Updated on: 16-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements