Disabling arrow key in text area using JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for disabling arrow key in text area 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-weight: 500;
      font-size: 18px;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Disabling arrow keys in a text area</h1>
<textarea class="AreaText">
Hello world this is some sample text inside the text area element
</textarea>
<div class="result"></div>
<button class="Btn" style="margin: 15px;">Disable arrows</button>
<h3>Click on the above button to disable scrolling using arrows in the above textArea</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   BtnEle.addEventListener("click", () => {
      window.addEventListener(
         "keydown",
         (event) => {
            if ([32, 37, 38, 39, 40].indexOf(event.keyCode) > -1) {
               event.preventDefault();
            }
         },
         false
      );
      resEle.innerHTML = "Scrolling using arrow keys is disabled";
   });
</script>
</body>
</html>

Output

On clicking the Disable arrows the scrolling wont work with arrows −

raja
Published on 16-Jul-2020 17:04:54
Advertisements