JavaScript: Detecting Caps lock

I wanted to see if you could detect caps lock in JavaScript. Why? As a small usability touch, basically alerting users that caps lock is enabled when they are entering passwords for example. I’ve wrapped up the logic in a simple function that can help you detect caps lock on a key press. Here is the demo and following is the function followed by a simple usage.

  1. function isCapslock(e){
  2.    
  3.     e = (e) ? e : window.event;
  4.    
  5.     var charCode = false;
  6.     if (e.which) {
  7.         charCode = e.which;
  8.     } else if (e.keyCode) {
  9.         charCode = e.keyCode;
  10.     }
  11.    
  12.     var shifton = false;
  13.     if (e.shiftKey) {
  14.         shifton = e.shiftKey;
  15.     } else if (e.modifiers) {
  16.         shifton = !!(e.modifiers & 4);
  17.     }
  18.    
  19.     if (charCode >= 97 && charCode <= 122 && shifton) {
  20.         return true;
  21.     }
  22.    
  23.     if (charCode >= 65 && charCode <= 90 && !shifton) {
  24.         return true;
  25.     }
  26.    
  27.     return false;
  28.    
  29. }
  30.  

  1.         <input type="text" name="testinput" id="testinput" value="" />
  2.        
  3.         <script type="text/javascript">
  4.            
  5.             document.getElementById(’testinput’).onkeypress = function(e){
  6.                
  7.                 if(isCapslock(e)){
  8.                    
  9.                     alert("Caps on");
  10.                    
  11.                 } else {
  12.                    
  13.                     alert("Caps off");
  14.                    
  15.                 }
  16.                
  17.             }
  18.            
  19.         </script>
  20.        

3 Responses to “JavaScript: Detecting Caps lock”

  1. Psychic Says:

    Great blog, subscribed to your rss feed. Thanks.

  2. Chris Says:

    Interesting. Good function, but the demo in its current state is non-usable because it brings up the box after every key stroke. Needless to say its annoying.

  3. Dougal Says:

    Very true. I’ve just changed it to make it a bit less annoying! Sorry about that, I guess I was being lazy.

Leave a Reply