Detect Caps Lock in Javascript

Any time when we need case-sensitive information from the user like email address or password as input, we want user to be aware of their caps lock status on the keyboard.

For that we need to detect caps lock state and notify user back.

Thus, in this tutorial we will see how to determine the caps lock is on or off in Javascript.

Learn more about DOM and its Manipulation with Javascript.

Using getModifierState()

The getModifierState() of keyboardevent returns the current state of the specified modifier key. True if modifier key is pressed or locked, otherwise false.

You can attach the keyboardevent like keydown, keypress or keyup on the document (to detect globally) or to the specific HTML element.

//HTML
<input type="email" id="email" />

//Javascript
const emailInput = document.querySelector("#email");

emailInput.addEventListener("keypress", function(event){
  if(event.getModifierState && event.getModifierState('CapsLock')){
    console.log("caps lock is on");
  }else{
    console.log("caps lock is off");
  }
});

This method is supported by all the major browsers.


But in case you want something to detect caps on older browser then you use this method.

//HTML
<input type="email" id="email" />

//Javascript
const isCapslock = (e) => {
  const IS_MAC = /Mac/.test(navigator.platform);

  const charCode = e.charCode;
  const shiftKey = e.shiftKey;

  if (charCode >= 97 && charCode <= 122) {
    capsLock = shiftKey;
  } else if (charCode >= 65 && charCode <= 90
    && !(shiftKey && IS_MAC)) {
    capsLock = !shiftKey;
  }

  return capsLock;
}

const emailInput = document.querySelector("#email");

emailInput.addEventListener("keypress", function(event){
  if(isCapslock(event)){
    console.log("caps lock is on");
  }else{
    console.log("caps lock is off");
  }
});