Checking for CapsLock in JavaScript

Home / Checking for CapsLock in JavaScript

Letting a user know that CapsLock is set can be a UI nicety. I needed this feature earlier today so I put together a demo.


Fortunately, when the CapsLock key is pressed by itself, it does trigger JavaScript Keydown events. The keycode (event.which) is 20 when CapsLock is pressed. However, we don’t know the CapsLock state, initially, from only the keydown event. We have to determine this for ourselves and track the state. The simplest method is to determine if an alpha character is typed and then compare that character with its upper case equivalent. If they are equal, and the shift key isn’t currently depressed, we then know that CapsLock is on.

Below is a demo Plunker that uses this concept and keydown/keypress events to set the CapsLock state. The simple form has a username and password entry. When the password input has focus and the CapsLock enabled state is true, a warning message is displayed to the user. The source for the JavaScript can be seen in the Plunker, but I’ve pasted it below the Plunker as well for posterity’s sake.

$(function() {
  var capsLockEnabled = null;
  document.msCapsLockWarningOff = true; // Set this to true to turn off default IE behavior. 
  var isCheckEnabled = document.msCapsLockWarningOff === undefined || document.msCapsLockWarningOff;

  var checkWarning = function() {
    if (capsLockEnabled) {
      $("#warning").show();
    } else {
      $("#warning").hide();
    }
  }

  if (isCheckEnabled) {
    $(document).keydown(function(e) {
      if (e.which == 20 && capsLockEnabled !== null) {
        capsLockEnabled = !capsLockEnabled;
        console.log("Keydown. CapsLock enabled: " + capsLockEnabled.toString());
      } else if (e.which == 20) {
        console.log("Keydown. Initial state not set.");
      }
    });

    $(document).keypress(function(e) {
      var str = String.fromCharCode(e.which);
      if (!str || str.toLowerCase() === str.toUpperCase()) {
        console.log("Keypress. Some control key pressed.");
        return;
      }
      capsLockEnabled = (str.toLowerCase() === str && e.shiftKey) || (str.toUpperCase() === str && !e.shiftKey);
      console.log("Keypress. CapsLock enabled: " + capsLockEnabled.toString());
    });

    $("#password").keyup(function(e) {
      checkWarning();
    });

    $("#password").on("focus", function(e) {
      checkWarning();
    });

    $("#password").on("blur", function(e) {
      console.log("Hiding warning")
      $("#warning").hide();
    });
  }

  console.log("Focusing username")
  $("#username").focus();
})

Leave a Reply