How to detect caps lock key turned on or not ?
KeyboardEvent: This Web API is used to deal with the user interaction by keyboard, the various event describes which kind of activity is been occurred.
- keydown: Fired when a key is pressed.
- keyup: Fired when a key is released.
The event which occurs due to the keyboard comes under KeyboardEvent Object.
Modifier Keys: These keys are used in conjunction with other keys to perform some special purpose or shortcut. There are two types of modifier keys that remain activated when pressed i.e. shift, ctrl, alt, etc. The other ones are those which are activated when pressed and deactivated when pressed again i.e. capslock, etc.
getModifierState: This is the method of the KeyboardEvent object and returns a boolean on whether the given modifier key is activated or not during that event.
const isActive = event.getModifierState(keyString); // It will return a boolean // keyString: A string to be passed i.e. "Alt", // "CapsLock", "Control", "NumLock", etc.
Example: Now we will detect whether the Capslock key is turned on or not. Here we are going to demonstrate a simple example in which we will detect the activation state of the caps lock key.
Step 1: Here we have created a simple HTML page that contains one div with some text and input elements and one paragraph to display warning text.
Step 2: This index.js file is attached in the script tag of the former HTML file. We are simply extracting the input element to add an event listener also we are extracting the warning text paragraph to change its style. After then we have passed a callback function to method addEventListener for “keyup” event. Inside that function, we are checking whether the caps lock key was turned on or when the key was released.
Output: This would be the output of the above code snippet, each time when we press the key it would generate an event on the key release.
Explanation: Here we have typed “abc” in starting as soon as we press the caps lock the event will generate and then the functionality detects it and changes that p element to appear. Again when we press caps lock the event will generate on the key release and functionality detects it, due to which next time when we will press any key the p tag will hide.