10

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

In a web form, is there any way to tell if the caps lock is on ?

I suppose I could check do a check onChange to see if all the characters are upper case. But is there a more direct way to do this?

Specifically, I am looking to implement a "YOUR CAPS LOCK IS ON" message when they enter the password field, similar to how the windows login screen does .

Community
  • 1
  • 1
Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168

1 Answers1

3

You can find a decent example of how to do this here: http://www.codeproject.com/KB/scripting/Detect_Caps_Lock.aspx

You could take that code and wrap it into a different kind of event, either, i.e. onfocus or on document load.

You can google for an index of key codes (I'd post a link, but I don't have high enough karma to post more than one link, sorry).

For simplicity the codes you'd be looking for is 20 (Caps lock).


Instructions copied here from site (license: CPOL)

Building the script

<script language="Javascript">
function capLock(e){
 kc = e.keyCode?e.keyCode:e.which;
 sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
 if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
  document.getElementById('divMayus').style.visibility = 'visible';
 else
  document.getElementById('divMayus').style.visibility = 'hidden';
}
</script>

Now we have our script ready to go. We now need to associate this script with our form.

Using the script

Let's add two items: a textbox and a DIV. Now we just need to call the onKeyPress event.

<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> 
Mottie
  • 84,355
  • 30
  • 126
  • 241
dmcnelis
  • 2,913
  • 1
  • 19
  • 28
  • 1
    This does not detect whether Caps Lock is on. It detects whether Caps Lock was turned on while on the page, but not if it was already on. – César Sep 19 '16 at 12:16
  • 6
    In 2017+, use [`event.getModifierState('CapsLock');`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState) - ([caniuse?](http://caniuse.com/#search=getModifierState)) – Mottie Mar 31 '17 at 12:50