Home About Me

How to Warn Users When Caps Lock Is On in JavaScript

Caps Lock has a habit of being turned on without the user noticing. In most text fields, that mistake is obvious right away, but in a password field it is much harder to spot. The result is familiar: a correct password gets entered in the wrong case, and the login fails for a frustrating reason.

A simple way to help is to detect whether Caps Lock is active while the user is typing. JavaScript can do that through KeyboardEvent and its getModifierState method:

document.querySelector('input[type=password]').addEventListener('keyup', function (keyboardEvent) {
    const capsLockOn = keyboardEvent.getModifierState('CapsLock');
    if (capsLockOn) {
        // 警告用户他们的caps锁定是打开的?
    }
});

In this example, a keyup listener is attached to a password input. Each time the user releases a key, getModifierState('CapsLock') checks the current state of Caps Lock and returns whether it is enabled. If it is, you can show a warning near the field or otherwise let the user know why their password may not be working.

What makes getModifierState useful is that it is not limited to Caps Lock. The method can report the state of several keyboard modifiers. The W3C definitions include values such as these:

dictionary EventModifierInit : UIEventInit {
  boolean ctrlKey = false;
  boolean shiftKey = false;
  boolean altKey = false;
  boolean metaKey = false;

  boolean modifierAltGraph = false;
  boolean modifierCapsLock = false;
  boolean modifierFn = false;
  boolean modifierFnLock = false;
  boolean modifierHyper = false;
  boolean modifierNumLock = false;
  boolean modifierScrollLock = false;
  boolean modifierSuper = false;
  boolean modifierSymbol = false;
  boolean modifierSymbolLock = false;
};

So while the immediate use case is warning users about accidental uppercase passwords, the broader takeaway is that getModifierState gives keyboard-focused events a surprisingly rich view of the current modifier keys. That can be handy anywhere keyboard state matters.