HTML onkeydown Event Attribute

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

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.

Syntax

<element onkeydown="script">

Values

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

Example

Type anything in the form below to trigger this event.

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

Browser Support

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

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 8th October 2023