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:
<input type="text" onkeydown="functionName()">
<input type="text" onkeypress="functionName()">
<input type="text" onkeyup="functionName()">
Introduction
There are three keyboard events in JavaScript that describe user interaction with the keyboard:
onkeydown
onkeypress
onkeyup
1. onkeydown
event
The event occurs when the user is pressing a key on the keyboard.
Practical example
In this example, we will execute myFunction()
on key down event inside the input
field.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<span>Type something:</span>
<input type="text" onkeydown="myFunction()"/>
<script>
function myFunction(){
console.log('onkeydown');
}
</script>
</body>
</html>
2. onkeypress
event
The event occurs when the user presses a key (when a character is being typed).
Practical example
In this example, we will execute myFunction()
on key press event inside the input
field.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<span>Type something:</span>
<input type="text" onkeypress="myFunction()"/>
<script>
function myFunction(){
console.log('onkeypress');
}
</script>
</body>
</html>
3. onkeyup
event
The event occurs when the user releases a key on the keyboard.
Practical example
In this example, we will execute myFunction()
on key up event inside the input
field.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<span>Type something:</span>
<input type="text" onkeyup="myFunction()"/>
<script>
function myFunction(){
console.log('onkeyup');
}
</script>
</body>
</html>
Differences
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:
// ONLINE-RUNNER:browser;
<!doctype html>
<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>