Open In App

HTML onkeydown Event Attribute

Last Updated : 20 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

swd

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:

wer

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


Next Article

Similar Reads