JavaScript - Keyboard Events
In this article, we would like to show you how to handle keyboard events and the differences between them in JavaScript.
Quick solution:
xxxxxxxxxx
<input type="text" onkeydown="functionName()">
xxxxxxxxxx
<input type="text" onkeypress="functionName()">
xxxxxxxxxx
<input type="text" onkeyup="functionName()">
There are three keyboard events in JavaScript that describe user interaction with the keyboard:
onkeydown
onkeypress
onkeyup
The event occurs when the user is pressing a key on the keyboard.
In this example, we will execute myFunction()
on key down event inside the input
field.
xxxxxxxxxx
<html>
<body>
<span>Type something:</span>
<input type="text" onkeydown="myFunction()"/>
<script>
function myFunction(){
console.log('onkeydown');
}
</script>
</body>
</html>
The event occurs when the user presses a key (when a character is being typed).
In this example, we will execute myFunction()
on key press event inside the input
field.
xxxxxxxxxx
<html>
<body>
<span>Type something:</span>
<input type="text" onkeypress="myFunction()"/>
<script>
function myFunction(){
console.log('onkeypress');
}
</script>
</body>
</html>
The event occurs when the user releases a key on the keyboard.
In this example, we will execute myFunction()
on key up event inside the input
field.
xxxxxxxxxx
<html>
<body>
<span>Type something:</span>
<input type="text" onkeyup="myFunction()"/>
<script>
function myFunction(){
console.log('onkeyup');
}
</script>
</body>
</html>
The main difference is the order in which the events occur. You can see it in the example below.
The order of keyboard events:
onkeydown
onkeypress
onkeyup
Runnable example:
xxxxxxxxxx
<html>
<body>
<span>Type something:</span>
<input type="text" onkeydown="handleKeyDown()" onkeypress="handleKeyPress()" onkeyup="handleKeyUp()" />
<script>
function handleKeyDown(){
console.log('onkeydown');
}
function handleKeyPress(){
console.log('onkeypress');
}
function handleKeyUp(){
console.log('onkeyup');
}
</script>
</body>
</html>