Detect Caps Lock with JavaScript

By  on  

Anyone is capable of having their caps lock key on at any given time without realizing so. Users can easily spot unwanted caps lock when typing in most inputs, but when using a password input, the problem isn't so obvious. That leads to the user's password being incorrect, which is an annoyance. Ideally developers could let the user know their caps lock key is activated.

To detect if a user has their keyboard's caps lock turn on, we'll employ KeyboardEvent's getModifierState method:

document.querySelector('input[type=password]').addEventListener('keyup', function (keyboardEvent) {
    const capsLockOn = keyboardEvent.getModifierState('CapsLock');
    if (capsLockOn) {
        // Warn the user that their caps lock is on?
    }
});

I'd never seen getModifierState used before, so I explored the W3C documentation to discover other useful values:

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;
};

getModifierState provides a wealth of insight as to the user's keyboard during key-centric events. I wish I had known about getModifier earlier in my career!

Recent Features

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

Incredible Demos

Discussion

  1. Great to know, thanks! Even has modifierHyper!

  2. Craig

    How about they just get rid of CAPS LOCK keys, or relegate them to a far off corner of the keyboard?

    It is the most useless key, taking up real estate in a valuable position.

    At a minimum, the OS should allow for a key re-assignment.

    I HATE CAPS LOCK keys. And did not use it once in this rant.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!