HTML onkeydown Event Attribute
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
Browser Support
The following information will show you the current browser support for the HTML onkeydown event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 8th October 2023
