HTML onkeydown Event Attribute
Last Updated :
20 Dec, 2023
The onkeydown event attribute works when the user presses any key from the keyboard. The onkeydown event is triggered when the down key is pressed down and used for capturing and responding to key events.
Syntax:Â
<element onkeydown = "script">
Supported Tags:
It supports all HTML elements EXCEPT-Â
Attribute Value:
This attribute contains single value script which works when any key pressed from the keyboard.Â
Example 1:Â
In this example we will see the implementation of onkeydown tag.
html
<!DOCTYPE html>
< html >
< head >
< title > HTML | onkeydown Event Attribute </ title >
< style >
h1 {
text-align: center;
color: green;
}
h2 {
text-align: center;
}
input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
font-size: 24px;
color: white;
}
p {
font-size: 20px;
}
</ style >
</ head >
< body >
< h1 >GeeksforGeeks</ h1 >
< h2 >onkeyup Event Attribute</ h2 >
< p >
Release the key to set
a green background color.
</ p >
< input type = "text" id = "demo" onkeydown = "keydownFunction()" onkeyup = "keyupFunction()" >
< script >
function keyupFunction() {
document.getElementById("demo").
style.backgroundColor = "blue";
}
function keydownFunction() {
document.getElementById("demo").
style.backgroundColor = "green";
}
</ script >
</ body >
</ html >
|
Output:Â
Output
Example 2:Â
In this example we will see the implementation of onkeydown tag.
HTML
<!DOCTYPE html>
< html >
< body >
< center >
< h1 style = "color:purple;font-weight:bold;" >
Key Press Example
</ h1 >
< p >
Press a key:
</ p >
< input type = "text"
onkeydown = "showKeyPress(event)" >
< p id = "keyInfo" ></ p >
< script >
function showKeyPress(event) {
var keyInfo = "Key Pressed: " + event.key;
document.getElementById("keyInfo").
innerHTML = keyInfo;
}
</ script >
</ center >
</ body >
</ html >
|
Output:
Output
Supported Browser:
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 6 and above
- Opera 12.1 and above
- Safari 1.2 and above
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...