Open In App

HTML | DOM KeyboardEvent

It refers to the events which occur when a key is pressed on the keyboard. 

Syntax:



<input type=”text” onkeypress/onkeydown/onkeyup=”function()/event”>

Events:The following events occur on pressing a key-



Properties:

Return Value: It returns events which occur when a given key is pressed from the keyboard. 

Example-1: Showing onkeypress event. 




<!DOCTYPE html>
<html>
 
<body>
 
    <h1>
      <center>Geeks for Geeks </center>
  </h1>
 
    <p>Type something in the box:</p>
 
    <input type="text" onkeypress="key()">
 
    <script>
        function key() {
            alert("New Key Inserted");
        }
    </script>
 
</body>
 
</html>

Output: 

Before Pressing a key:

  

After Pressing a key:

  

 

Example-2: Showing onkeydown event. 




<!DOCTYPE html>
<html>
 
<body>
 
    <h1>
      <center>Geeks for Geeks </center>
  </h1>
 
    <p>Type something in the box:</p>
 
    <input type="text" onkeydown="key()">
 
    <script>
        function key() {
            alert("New Key Inserted");
        }
    </script>
 
</body>
 
</html>

Output: 

Before Pressing a key:

  

After Pressing a key: 

 

 

Example-3: To check if the pressed key is Alt or not. 




<!DOCTYPE html>
<html>
 
<body>
 
    <h1>
      <center>Geeks for Geeks </center>
  </h1>
 
    <p>Type something in the box to
      check if Alt key is pressed or not:</p>
 
    <input type="text" onkeydown="isKeyPressed(event)">
 
    <p id="gfg"></p>
 
    <script>
        function isKeyPressed(event) {
            var x = document.getElementById("gfg");
            if (event.altKey) {
                x.innerHTML = "ALT Key Pressed";
            } else {
                x.innerHTML = "ALT Key Not Pressed";
            }
        }
    </script>
 
</body>
 
</html>

Output: 

Before Pressing a key:

  

After Pressing a key:

  

Example-4: To find out the pressed key from the keyboard. 




<!DOCTYPE html>
<html>
 
<body>
 
    <h1>
      <center>Geeks for Geeks </center>
  </h1>
 
    <p>Type something in the box
      to know the entered key:</p>
 
    <input type="text"
           size="40"
           onkeydown="myFunction(event)">
 
    <p id="gfg"></p>
 
    <script>
        function myFunction(event) {
            var x = event.key;
           
            document.getElementById(
              "gfg").innerHTML =
              "Entered Key is: " + x;
        }
    </script>
 
</body>
 
</html>

Output: 

Before Pressing a key:

  

After Pressing a key:

  

Browser Support: The listed browsers support DOM Keyboard Event-


Article Tags :