In this article, we’ll delve into capturing and responding to various keyboard events in JavaScript. I’ll present real-world examples to make the concept more comprehensible. JavaScript is one of the core technologies of the Web, and it’s supported by all modern browsers without requiring plugins. Throughout this Series. we’ll explore different tips and techniques that can enhance your dAIly JavaScript development.
As a JavaScript developer, there might be instances where you need to implement functionalities that involve handling keyboard events and executing Actions based on them. Fortunately, JavaScript provides a built-in KeyboardEvent object, enabling you to manage different types of keyboard events.
### Keyboard Events in JavaScript
The KeyboardEvent object offers three events: `keydown`, `keypress`, and `keyup`.
1. **keydown**: This event is triggered when any key is pressed on the keyboard. If a key is held down, the `keydown` event will repeat. It mainly fires for printable characters and is followed by the `keypress` event. Depending on the browser, non-character keys may not trigger a `keydown` event.
2. **keypress**: Now deprecated, this event was primarily used to detect character input. It will be phased out in modern browsers. It occurs after `keydown` and before `keyup`. Avoid relying on it due to its impending rEMOval from web standards.
3. **keyup**: This event is triggered when a key is released. It follows the sequence of `keydown` and `keypress` events.
Each keyboard event has two essential properties: `key` and `code`. The `key` property is filled with the pressed character, while the `code` property reflects the physical key position. For instance, pressing the ‘A’ character key will fill `key` with ‘A’ and `code` with the constant `KeyA`. However, the key code doesn’t necessarily match the character if alternative keyboard layouts like Dvorak are set.
Let’s now explore these events through practical examples to understand how they function.
#### Keydown Event
The `keydown` event is triggered when any key is pressed on the keyboard. Here’s a quick example:
“`javascript
document.addEventListener(‘keydown’, (event) => {
var keyValue = event.key;
var codeValue = event.code;
console.log(“key value: ” + keyValue);
console.log(“code value: ” + codeValue);
}, false);
“`
In this snippet, we create an event listener for `keydown`. Whenever a key is pressed, our listener is called, logging the key and code values to the console.
#### Detecting Ctrl+A or CTRL+A
Here’s an example demonstrating how to detect if the user presses `Ctrl+A` or `CTRL+A`:
“`javascript
document.addEventListener(‘keydown’, (event) => {
if (event.ctrlKey) {
if (event.keyCode === 65 || event.keyCode === 97) {
console.log(“You just pressed Ctrl + a/A!”);
}
}
}, false);
“`
The `ctrlKey` property of the KeyboardEvent object indicates whether the Ctrl key was pressed during the `keydown` event. If `ctrlKey` is true, the Ctrl key was pressed. We then check the `keyCode` property to determine if A or a (65 or 97) was pressed alongside the Ctrl key.
#### Allowing Only Letters in an Input Field
This example shows how to allow only letters in an HTML form input field:
“`javascript
function allowOnlyAlphabets(event) {
const keyCode = event.keyCode;
if (keyCode >= 65 && keyCode = 97 && keyCode {
var keyValue = event.key;
var codeValue = event.code;
console.log(“keydown event, key value: ” + keyValue);
console.log(“keydown event, code value: ” + codeValue);
}, false);
document.addEventListener(‘keyup’, (event) => {
var keyValue = event.key;
var codeValue = event.code;
console.log(“keyup event, key value: ” + keyValue);
console.log(“keyup event, code value: ” + codeValue);
}, false);
“`
In this example, both `keydown` and `keyup` events are logged. You’ll notice that the `keyup` event follows the `keydown` event.
#### Important KeyboardEvent Object Properties
– **key**: Returns the character pressed. For example, pressing ‘A’ returns ‘A’.
– **code**: Returns the physical key code of the character. For ‘A’, it returns ‘KeyA’.
– **keyCode**: Returns the Unicode character code of the pressed key. For ‘A’, it returns 65.
– **ctrlKey**: Indicates if the Ctrl key was pressed during the key event.
– **altKey**: Indicates if the Alt key was pressed during the key event.
– **shiftKey**: Indicates if the Shift key was pressed during the key event.
– **metaKey**: Indicates if the Meta key was pressed during the key event. In most cases, this refers to the key between Ctrl and Alt.
In conclusion, we’ve discussed how to use keyboard events in JavaScript and showcased some practical examples. Remember, `keydown` is typically used to detect pressed keys, while `keypress` should be avoided due to its deprecation. Keep exploring other related articles for more insights into JavaScript!