Definition:
When you press a key on the keyboard, the action starts immediately.
The action keeps repeating as long as you hold the key.
For example, if you press the ‘A’ key, the action begins immediately and continues to repeat as long as you press the key.
This event occurs on input boxes, textareas, or other focusable HTML elements.
List of focusable HTML elements:
<input>– text, password, search boxes<textarea>– multi-line text box<button>– buttons<select>– dropdown boxes<a href="#">– links- Any element with
tabindex="0"– for example, a normal <div> or <span> can become focusable when you addtabindex="0".
Now you will clearly understand with the help of the flowchart.
Start
|
v
User presses a key
|
v
Browser detects onkeydown event
|
v
Is there a function assigned?
|
|-- Yes --> Run the function continuously
| while the key is held
| |
| v
| Action repeats
| |
| v
| End
|
|-- No --> Nothing happens
|
v
End
Syntax:
In HTML:
<input type="text" onkeydown="myFunction()">
In JavaScript:
document.getElementById("myInput").onkeydown = function(event) {
console.log("Key pressed: " + event.key);
};
Example:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="box" onkeydown="showText()"
placeholder="You type here.">
<p id="result"></p>
<script>
function showText() {
document.getElementById("result").innerHTML =
"you press any key, like the “A” key,";
}
</script>
</body>
</html>
Output:
