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

None.

Syntax

<element onkeydown="script">

Supported Tags

All HTML elements, EXCEPT:

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




Browser compatibility

onkeydown Yes Yes Yes Yes Yes

Example

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

<script>
function myFunction() {
    console.log("pressed a key");
}
</script>

</body>
</html>

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.

<html>
<head>
<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);
  }
</script>
</head>
<body onkeydown="press()">
  <P>
    <textarea id="txt1" rows="15" cols="50"></textarea>
  </p>
</body>
</html>

Click to view the demo