
Detect or Check Caps Lock Key is ON or OFF using JavaScript
To detect whether the Caps Lock key is on or off using JavaScript, you can listen for the keydown
or keypress
event and check the event.getModifierState()
method. Here’s an example:
document.addEventListener('keydown', function(event) {
var capsLockOn = event.getModifierState('CapsLock');
if (capsLockOn) {
console.log('Caps Lock is ON');
} else {
console.log('Caps Lock is OFF');
}
});
In the example above, we attach an event listener to the keydown
event on the document
object. When a key is pressed, the event handler function is called. Inside the function, we use the getModifierState()
method to check if the Caps Lock key is on or off. If it is on, we log a message indicating that Caps Lock is ON; otherwise, we log a message indicating that Caps Lock is OFF.
Note that the getModifierState()
method can also be used to check the state of other modifier keys such as Shift, Ctrl, Alt, and Meta (Windows key or Command key on macOS). Simply replace 'CapsLock'
with the desired key identifier.
Keep in mind that not all keyboards or operating systems provide the ability to detect the Caps Lock state through JavaScript. The availability and accuracy of detecting the Caps Lock key may vary across different browsers and platforms. Therefore, it’s important to consider this when using Caps Lock detection in your application and provide alternative user interface cues if needed.