How to Find Out if Capslock is on Inside an Input Field With JavaScript

As a software developer, it is essential to know how to detect if the caps lock key is on or off inside an input field.

This can be useful for creating password fields where the user needs to be aware if the caps lock is on or off, as this could cause their password to be typed incorrectly.

In this tutorial, we will go over how to check if caps lock is on inside an input field using JavaScript.


Understanding Key events in JavaScript

To detect if caps lock is on or off, we need to understand the key events in JavaScript.

Key events in JavaScript are events that are triggered by the user’s keyboard.

There are several key events, including keydown, keypress, and keyup.

These events provide information about the key that was pressed and whether any modifiers, such as shift or caps lock, were also pressed.

Using the KeyPress Event

The keypress event is triggered when a character key is pressed down and then released.

It provides information about the character that was typed, as well as any modifier keys that were also pressed.

To check if the caps lock is on, we can use the keypress event to check the character that was typed and compare it to the character that would have been typed if caps lock was off.

const inputField = document.querySelector("input");
inputField.addEventListener("keypress", function(event) {
let charCode = event.charCode;
if (charCode >= 65 && charCode <= 90 && !event.shiftKey) { console.log("Caps lock is on."); } else if (charCode >= 97 && charCode <= 122 && event.shiftKey) {
console.log("Caps lock is on.");
} else {
console.log("Caps lock is off.");
}
});

In the code above, we first select the input field using document.querySelector(“input”).

We then add a keypress event listener to the input field. In the event listener, we use event.charCode to get the character code of the key that was pressed.

We then use an if statement to check if the character code is between 65 and 90 (A-Z) and the shift key was not pressed, or if the character code is between 97 and 122 (a-z) and the shift key was pressed.

If either of these conditions is met, we log a message to the console saying that caps lock is on.

If neither of these conditions is met, we log a message saying that caps lock is off.


Conclusion

In this blog post, we went over how to check if caps lock is on inside an input field using JavaScript.

We used the keypress event to get information about the key that was pressed and used an if statement to check if the caps lock was on or off.

By understanding key events in JavaScript and using the keypress event, you can easily detect if the caps lock key is on or off inside an input field.