HTML onkeydown Event Attribute


The onkeydown HTML event attribute specifies a JavaScript function to be executed when the user presses a key on the keyboard. It is fired for all keys, regardless of whether they produce a character value. This is in contrast to the keypress event, which is only fired for keys that produce character values.

The onkeydown event is supported by all HTML elements except <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>.

To use the onkeydown event attribute, simply add it to the HTML element you want to listen for the event on. The value of the attribute should be the name of the JavaScript function to be executed when the event is fired.

For example, the following code will execute the myFunction() function when the user presses any key while focused on the input element:

<input type="text" onkeydown="myFunction()">

The onkeydown event can be used to implement a variety of features, such as:

  • Keyboard shortcuts
  • Form validation
  • Interactive games and simulations

Here is an example of a simple JavaScript function that can be used to implement a keyboard shortcut:

function myFunction() {
  // Do something when the user presses a key

The myFunction() function can be assigned to the onkeydown event attribute of any HTML element. When the user presses a key while focused on that element, the myFunction() function will be executed.


<element onkeydown="script">


  • scriptThe name of the script to use when the event has been triggered.


Type anything in the form below to trigger this event.

<!DOCTYPE html>
<title>Event Attribute onkeydown</title>
<p>Click any button in the form to run the script:</p>
<input type="text" onkeydown="keyboardTest()">
function keyboardTest() {
alert("EXAMPLE: You see this window because you triggered the script");

Browser Support

The following table will show you the current browser support for the HTML onkeydown Event Attribute.

Edge Chrome Firefox Opera Safari
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview

Last updated by CSSPortal on: 8th October 2023