JavaScript - Detecting the pressed arrow key

JavascriptFront End TechnologyObject Oriented Programming

To detect the pressed arrow key in JavaScript, the code is as follows;

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;
}
.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 −

raja
Published on 06-May-2020 11:45:53
Advertisements