What is OnKeydown?
In JavaScript, the Onkeydown event handler is triggered whenever an individual presses a key on the keyboard. This event can be utilized with a variety of elements, particularly those where users are able to enter characters, such as in form fields, text areas, or text boxes.
It specifies the expected behavior when a key is pressed while the document's object is currently focused. To retrieve the key that was pressed, it is necessary to utilize the keyCode along with the relevant event properties.
Syntax
Let us examine the syntax associated with the onkeydown event handler in JavaScript:
<input type = "text" onkeydown = "myFunction()">
event.code and event.key
The key properties of the event object enable us to access the character, whereas the code property permits us to obtain the physical key code.
Consider a scenario where we have a key labeled A that can be activated with or without the Shift key. Depending on whether the Shift key is engaged, this action will produce two distinct characters:
Lowercase (a) and Uppercase (A)
When a user operates in an alternative language, the output will yield a distinct character in place of A. The value corresponding to the event.key will vary, while the event.code will remain unchanged consistently.
Note: the event.code indicates the specific key that gets pressed. For instance, most keyboards have two Shift keys, one on the left and the other on the right. The event.code helps us identify which one of them was pressed. Meanwhile, the event.key is responsible for defining the function of the key such as whether it's a Shift key.
By utilizing this, we can determine which key has been pressed; it is necessary to establish a listener for the keydown event.
On one side, if the value of event.key corresponds to a character, it will vary based on the language settings. When a user has multiple languages configured in the operating system and switches between them, the same key can produce different characters. Therefore, it is essential to ensure that the value of event.code remains consistent at all times.
For 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>
</head>
<script>
function myFunction(){
alert("You pressed a key now.")
}
</script>
<body>
<input type="text" onkeydown="myFunction()">
</body>
</html>
Output:
Auto-repeat
When a key is held down for an extended duration, it begins to auto-repeat: the keydown event will be triggered repeatedly, and only upon its release do we receive the keyup event.
In our scenario, we observe that there are several keydown events occurring, while only a single keyup event is generated, which is typical behavior. To enable the event to be activated through auto-repeat functionality, it is essential to examine the event object and verify whether the event.repeat property is assigned a value of true.
Default Actions
We have different default actions. It is because we may have possible things that can be initiated by the keyboard, as described below:
- A character can come out of the screen.
- A character is deleted by the delete key.
- Scrolling can be done with the page-down key.
- The save page dialog can be opened with Ctrl+S.
When we inhibit the default behavior during a keydown event, it can effectively suppress the majority of key actions, with the exception of certain operating system-specific keys. For instance, on Windows, the combination Alt+F4 is utilized to terminate the active browser window. In JavaScript, it is not possible to halt this action by merely preventing the default behavior.
Example 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function checkedPhoneKey(key) {
return(key >= '0' && key <= '9') || key == '+' || key == '(' || key ==')' || key == '-';
}
</script>
<input onkeydown = "return checkedPhoneKey(event.key)" placeholder = "Phone number" type="tel">
</body>
</html>
Output:
Example 2:
<!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>
h1{
text-align: center;
color: yellowgreen;
}
h2 {
text-align: center;
}
input [type= text]{
width: 100%;
padding: 14px 22px;
margin: 7px 0;
box-sizing: border-box;
font-size: 22px;
color: white;
}
p{
font-size: 22px;
}
</style>
</head>
<body>
<h1>Event handler</h1>
<h2>Sample output</h2>
<p>Press the key to change the background color</p>
<input type="text" id="demo" onkeydown="func1()"
onkeyup="func2()">
<script>
function func2(){
document.getElementById("demo").style.backgroundColor = "red";
}
function func1 (){
document.getElementById("demo").style.backgroundColor = "orange";
}
</script>
</body>
</html>
Output:
Example 3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Event Handler</h1>
<h2>Sample output</h2>
<input type="text" id="demo" onkeydown= "func1()">
<script>
function func1(){
var keyCode = ('which' in event) ? event.which : event.keycode;
alert("The Unicode key code is:" + keyCode);
}
</script>
</body>
</html>
Output:
Example 4:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScritp onkeydown event handler</title>
<style>
h1{
text-align: center;
color: bisque;
}
h2{
text-align: center;
}
input[type=text] {
width: 100%;
padding: 14px 22px;
margin: 7px 0;
box-sizing: border-box;
font-size: 22px;
color: white;
}
p{
font-size: 22px;
}
</style>
</head>
<body>
<h1>Event handler</h1>
<h2>Sample output</h2>
<p> Press the key to change the background color and print the unicode</p>
<input type="text" id="demo" onkeydown="func1()">
<script>
function func2(){
document.getElementById("demo").style.backgroundColor = "red";
}
function func1() {
var keyCode = ('which' in event) ? event.which: event.keyCode;
alert ("The Unicode key code is:" +keyCode);
document.getElementById("demo").style.backgroundColor = "blue";
}
</script>
</body>
</html>
Output: