Skip to content

Detect CAPS LOCK with JavaScript

Detect Caps Lock with JavaScript

Sometimes it’s possible to have Caps Lock on without realizing it.

It’s even more frustrating when this happens while creating a password.

That’s why some applications choose to warn their users when Caps Lock is on.

I’ll show you a simple way to implement a method to detect if the user has Caps Lock on.

Play around with the demo:

See the Pen Untitled by Carol-Theodor Pelu (@Tynael) on CodePen.

We can detect the Caps Lock key by using the getModifierState() method that is available on the keyboardEvent.

I chose to use the 'keyup' event but 'keydown' can also work in some scenarios.

  let warningMessage = document.getElementById('warning-message');
  let passwordInput = document.getElementById('password-input');

  passwordInput.addEventListener("keyup", (keyboardEvent) => {
      const isCapsLockOn = keyboardEvent.getModifierState("CapsLock");

      if (isCapsLockOn) {
          warningMessage.style.display = "block";
      } else {
          warningMessage.style.display = "none";
      }
  })

🎥 Watch the video for a full walkthrough:


Let me know what you think about this article in the comments section below.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.   
  

Comments