HTML | DOM onkeydown Event

The DOM onkeydown event in HTML occurs when a key is pressed by the user.

Order of events related to the onkeydown event:

  • onkeydown
  • onkeypress
  • onkeyup

Supported HTML tags: All HTML elements, EXCEPT:



  • <base>
  • <bdo>
  • <br>
  • <head>
  • <html>
  • <iframe>
  • <meta>
  • <param>
  • <script>
  • <style>
  • <title>

Syntax:

  • In HTML:
    <element onkeydown="myScript">>
  • In JavaScript:
    object.onkeydown = function(){myScript};
  • In JavaScript, using the addEventListener() method:
    object.addEventListener("keydown", myScript);

Example: onkeydown Event using the addEventListener() method

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body>
    <center>
        <h1 style="color:green">
          GeekforGeeks
      </h1>
        <p>Press any key inside the input field</p>
  
        <input type="text"
               id="inputField"
               style="background-color:green">
  
        <script>
            document.getElementById(
              "inputField").addEventListener("keydown", GFGFun);
  
            function GFGFun() {
                document.getElementById(
                  "inputField").style.backgroundColor = 
                  "yellow";
  
            }
        </script>
    </center>
</body>
  
</html>

chevron_right


Output:
Before:

After:

Supported Browsers: The browsers supported by HTML DOM onkeydown Event are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.