HTML event attribute onkeydown

The onkeydown attribute event is triggered when the user pressed a key.

The order of events related to the onkeydown event:

  • onkeydown
  • onkeypress
  • onkeyup

What's new in HTML5



<element onkeydown="script">

Supported Tags

All HTML elements, EXCEPT:


Browser compatibility

onkeydown Yes Yes Yes Yes Yes


<!DOCTYPE html>
<!--from   ww w .  j a  va2  s  . com-->
<input type="text" onkeydown="myFunction()">

function myFunction() {
    console.log("pressed a key");


Click to view the demo

Example 2

The following code adds event handlers for key down event in the body tag and output the key char converted from key code.

<script type="text/javascript">
  function press() {<!--from w ww  .jav  a2  s. c o  m-->
    var oTextbox = document.getElementById("txt1");
    oTextbox.value += "\n>" + String.fromCharCode(event.keyCode);
<body onkeydown="press()">
    <textarea id="txt1" rows="15" cols="50"></textarea>

Click to view the demo