Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Detect Caps Lock with JavaScript

4.37/5 (13 votes)
16 Jan 2007CPOL 1  
How to detect CapsLock with Javascript.

Introduction

I'm sure that this script will help you in some of your projects that needs a username and password.

Sometimes when we want access to a secure page that asks for a username and password and we submit the information but we didn't know that the password was submitted in upper case, we get an error.

Solution

We can avoid this kind of problems by just adding some JavaScript code to our page.

Building the script

HTML
<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.

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

See if it works on your project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)