How to Detect Caps Lock Status with JavaScript?

One event that happens to every computer user at least once is forgetting the Caps Lock key turned on. There are actually times we do this intentionally. For example, when we’re angry during a chat/conversation, we write in uppercase letters. Maybe we had to write that way because we forgot it was on. Let’s consider another example: entering a username and password, especially in the password input, this can cause a lot of confusion.

In both of the above usage examples, we can provide a better UX by detecting the state of the Caps Lock key:

  • When detected on the chat screen, we can give a warning asking if you’re really angry 🙂
  • When entering a password, we can provide a small warning below the input..

These are the first uses that come to mind, but I’m sure there are many other applications.

How Will We Detect the Caps Lock State?

To detect whether a user’s keyboard Caps Lock key is on or off, we will use the getModifierState method of KeyboardEvent:

document.querySelector('input').addEventListener('keyup', function (keyboardEvent) {
    const capsLockOn = keyboardEvent.getModifierState('CapsLock');
    if (capsLockOn) {
        // You can perform your magic from this point forward.
    }
});

In fact, through getModifierState, we can also learn about the status of many keys. Maybe you can use it to place an easter egg on your site with different key combinations or to do secret tasks. When we examine the W3C documentation, you can follow the status of keys like ‘ctrl’, ‘alt’, ‘shift’, ‘fn’, ‘fnLock’, ‘hyper’, ‘numLock’, ‘scrollLock’, and so on.