What you will learn?
- Detecting the status of the Caps Lock key
The KeyboardEvent Object
To understand how to detect the Caps Lock status, we must first understand the KeyboardEvent object. Whenever a user interacts with the keyboard, such as when pressing or releasing a key, a KeyboardEvent is fired. This event carries useful information about the key pressed, whether any ‘modifier’ keys like Shift or Ctrl are pressed, and more.
Caps Lock Detection
To detect the status of the Caps Lock key, we can use the getModifierState() method that is available on the KeyboardEvent object. This method returns a Boolean value that indicates whether a modifier key such as Caps Lock is active. The method accepts one argument, which is a string representing the modifier key.
Here’s a basic example of using getModifierState() to detect the Caps Lock status:
In the example above, we’re attaching an event listener to the document that listens for the ‘keydown’ event. The callback function receives the event object. We then call `event.getModifierState(‘CapsLock’)`, which will return true if the Caps Lock key is active and false otherwise.
Implementing Visual Indicators for Caps Lock
Detecting Caps Lock status is most beneficial when implemented with real-time user feedback, such as during password input. Let’s create a function that shows a warning message when Caps Lock is on:
In this code, we have an input field with the ID ‘password’, and a warning message with the ID ‘caps-warning’. When the Caps Lock key is on, the warning message is displayed. When the Caps Lock key is off, the warning message is hidden.
Create an HTML Page
Here’s an HTML demo that includes an input field for a password and a warning message that appears when the Caps Lock key is turned on. You can also view this demo here:
In this demo, the warning message is hidden by default using CSS (display: none). The script listens for the ‘keyup’ event on the password input field, and if the Caps Lock is on, it changes the CSS of the warning message to `display: block`, showing the warning message. If the Caps Lock is turned off, it hides the warning message again by setting `display: none`.
Points to Remember
This approach only detects whether the Caps Lock key is on at the time of the key press. It does not continually monitor the status of the key.
The Caps Lock status can vary between different devices and operating systems. Always ensure your implementation works across different environments.