Detect caps lock on/off using jQuery

ACP picture ACP · Feb 22, 2010 · Viewed 46.1k times · Source

How can I detect the Caps Lock key on/off using jQuery? I have a password textbox, and I allow only lowercase letters so I don't want the Caps Lock key to be on.

Is it possible to detect the state of Caps Lock key using jQuery?

Answer

twodayslate picture twodayslate · Feb 22, 2010

How to detect Caps Lock with Javascript.

function capLock(e){
  var kc = e.keyCode ? e.keyCode : e.which;
  var sk = e.shiftKey ? e.shiftKey : kc === 16;
  var visibility = ((kc >= 65 && kc <= 90) && !sk) || 
      ((kc >= 97 && kc <= 122) && sk) ? 'visible' : 'hidden';
  document.getElementById('divMayus').style.visibility = visibility
}

Then for your password form:

<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div>