All TalkersCode Topics

Follow TalkersCode On Social Media

Enable And Disable Keyboard Keys Using JavaScript

Last Updated : Apr 15, 2022

IN - JavaScript HTML

In this tutorial we will show you how to enable and disable keyboard keys using JavaScript. User can disable and enable all the typing keys on keyboard by clicking on enable and disable buttons.

You may also like enable disable submit button using jQuery.

Enable And Disable Keyboard Keys Using JavaScript

To Enable And Disable Keyboard Keys It Takes Only One Step:-

  1. Make a HTML file and define markup, scripting and styling

Step 1. Make a HTML file and define markup, scripting and styling

We make a HTML file and save it with a name enable_disable.html

<html>
<head>
<script type="text/javascript">
function disable()
{
 document.onkeydown = function (e) 
 {
  return false;
 }
}
function enable()
{
 document.onkeydown = function (e) 
 {
  return true;
 }
}
</script>
<style>
body
{
 margin:0 auto;
 padding:0px;
 text-align:center;
 width:100%;
 font-family: "Myriad Pro","Helvetica Neue",Helvetica,Arial,Sans-Serif;
 background-color:#21618C;
}
#wrapper
{
 margin:0 auto;
 padding:0px;
 text-align:center;
 width:995px;
}
#wrapper h1
{
 margin-top:50px;
 font-size:45px;
 color:#FDF2E9;
}
#wrapper h1 p
{
 font-size:18px;
}
#text_div textarea
{
 width:350px;
 height:100px;
 padding:10px;
}
#text_div input[type="button"]
{
 width:100px;
 height:35px;
 margin-top:5px;
 background:none;
 border:1px solid white;
 color:white;
 font-weight:bold;
}
</style>
</head>
<body>
<div id="wrapper">

<div id="text_div">
<textarea placeholder="Enter Text"></textarea>
<input type="button" value="DISABLE" onclick="disable();">
<input type="button" value="ENABLE" onclick="enable();">
</div>

</div>
</body>
</html>

In this step we create a textarea to test keyboard before and after disabling and enabling. We create two buttons to disable and enable keyboard and we also create two functions disable() and enable() and use onkeydown() function to track keypress and use false and true respectively.

You may also like disable cut, copy and paste using jQuery.

That's all, this is how to enable and disable keyboard keys using JavaScript. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Latest Tutorials