Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
| Event | Description |
|---|---|
| Onkeydown | This event fires when the user is pressing a key |
| Onkeypress | This event fires when the user presses the key |
| Onkeyup | This event fires when the user releases the key. |
Following is the code for key events in JavaScript −
Example
<!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 −

Advertisements