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
JavaScript - Detecting the pressed arrow key
To detect the pressed arrow key in JavaScript, the code is as follows;
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;
}
.sample {
font-size: 18px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Detecting the pressed arrow key</h1>
<div class="sample"></div>
<h3>
Press any arrow key to know which arrow key has been pressed
</h3>
<script>
let fillEle = document.querySelector(".sample");
document.body.addEventListener("keydown", (event) => {
switch (event.keyCode) {
case 37:
fillEle.innerHTML = "Left key pressed";
break;
case 38:
fillEle.innerHTML = "Up key pressed";
break;
case 39:
fillEle.innerHTML = "Right key pressed";
break;
case 40:
fillEle.innerHTML = "Down key pressed";
break;
}
});
</script>
</body>
</html>
Output

On pressing any of the arrow key −

Advertisements