javascriptkeyboardcapslock

How do you tell if caps lock is on using JavaScript?


How do you tell if caps lock is on using JavaScript?

One caveat though: I did google it and the best solution I could find was to attach an onkeypress event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lock must be on. This feels really dirty and just... wasteful - surely there's a better way than this?


Solution

  • You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)

    NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.

    OLD VERSION: https://jsbin.com/mahenes/edit?js,output

    Also, here is a modified version (can someone test on mac and confirm)

    NEW VERSION: https://jsbin.com/xiconuv/edit?js,output

    NEW VERSION:

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

    OLD VERSION:

    function isCapslock(e) {
      e = (e) ? e : window.event;
    
      var charCode = false;
      if (e.which) {
        charCode = e.which;
      } else if (e.keyCode) {
        charCode = e.keyCode;
      }
    
      var shifton = false;
      if (e.shiftKey) {
        shifton = e.shiftKey;
      } else if (e.modifiers) {
        shifton = !!(e.modifiers & 4);
      }
    
      if (charCode >= 97 && charCode <= 122 && shifton) {
        return true;
      }
    
      if (charCode >= 65 && charCode <= 90 && !shifton) {
        return true;
      }
    
      return false;
    }
    

    For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...

    uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'

    The above keys are just sample representation.