Detect caps lock on/off using jQuery

Viewed 47274

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?

6 Answers

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> 

What I do is put up a warning when

  1. the username or password is incorrect and
  2. the username or password provided was all upper-case.

It's a pretty bad idea to only allow smaller letters. You're cutting down the number of possible passwords by a tremendous amount by doing that.

Related