Keyboard Events in JavaScript (Live Playground)
In this tutorial, we'll explore how to work with keyboard events in JavaScript to create interactive web applications that respond to user inputs, such as key presses and releases.
Common keyboard events
Here are some common keyboard events you might encounter when working with JavaScript:
keydown
: Triggered when a user presses a key on the keyboard.keyup
: Triggered when a user releases a key on the keyboard.keypress
: Triggered when a user presses a key on the keyboard that produces a character value.
Handling keyboard events
To handle keyboard events in JavaScript, you can use the addEventListener()
method. Here's an example of how to handle the keydown
event:
<!DOCTYPE html>
<html>
<head>
<title>Keyboard Events Example</title>
</head>
<body>
<input type="text" id="myInput" placeholder="Type something..." />
<script>
// Get a reference to the input element
var input = document.getElementById('myInput');
// Function to handle the keydown event
function handleKeydown(event) {
console.log('Key pressed:', event.key);
}
// Add a keydown event listener to the input
input.addEventListener('keydown', handleKeydown);
</script>
</body>
</html>
In this example, we define a handleKeydown()
function that logs the pressed key in the console. We then use the addEventListener()
method to register the handleKeydown()
function as a callback for the keydown
event on the input element.
Example: Detecting the Enter key
Now let's create an example where we detect when the Enter key is pressed:
<!DOCTYPE html>
<html>
<head>
<title>Detect Enter Key Example</title>
</head>
<body>
<input type="text" id="myInput" placeholder="Press Enter when done..." />
<script>
// Get a reference to the input element
var input = document.getElementById('myInput');
// Function to handle the keyup event
function handleKeyup(event) {
if (event.key === 'Enter') {
console.log('Enter key pressed!');
}
}
// Add a keyup event listener to the input
input.addEventListener('keyup', handleKeyup);
</script>
</body>
</html>
In this example, we define a handleKeyup()
function that checks if the released key is the Enter key. If it is, we log a message. We then use the addEventListener()
method to register the handleKeyup()
function as a callback for the keyup
event on the input element.