There are quite a few scripts out there for checking whether the Caps Lock key is on. However, the top searches for a helpful JavaScript function turn up a lot of dated, obsolete code that usually doesn’t work or uses techniques that are frowned upon, such as obtrusive JavaScript.

In this article I will show you a modern, unobtrusive, cross-browser way of detecting Caps Lock.

What’s this for?

This technique is intended for use on login screens where usernames and passwords are case-sensitive. If the user begins typing into a field with the Caps Lock on, the web page can notify them before an invalid login attempt.

Looking through older comments on the subject, some people are using Caps Lock detection to alter the case of input for one reason or another. I can’t think of any legitimate reason to do so, nor would I ever forcefully alter a user’s input (it’s just rude).

How does it work?

This script uses JavaScript event handlers to determine if Caps Lock is engaged when the keyboard begins typing into a designated field. Other scripts for this tend to put the JavaScript inline obtrusively using onkeypress or another key handler. This solid script is more graceful, as you simply assign a CSS class to your username and/or password field and the script does the rest.

The simplest way of notification would be an alert() box that simply displays a message. However, it would be a lot more user-friendly to have a div element next to the field itself that will appear when the Caps Lock key is on.

Demo Page

Check out this Caps Lock detector script live in action in your choice of flavors:

plain demo page or the fancy demo page.

This script has been tested for cross-browser compatibility in the following browsers:

  • IE7, IE8, IE9
  • Firefox
  • Chrome
  • Safari
  • Opera

Cross-Browser Caps Lock Detection

Below is a full script that you can drop in to your project. This script will automatically initialize on load, and will not compromise any existing onload events.

If you are using a framework like JQuery or MooTools, you can remove the first block of code below and simply call loadCapsChecker from your framework’s DOM ready function.

Usage: Drop this script into your project, add the CSS class to your input elements, and optionally add the CSS class to your warning notice element. The default class names are capLocksCheck and capLocksNotice. If you don’t have a warning message element, the script will create a pop up alert message for you.

JAVASCRIPTview code
 
var existing = window.onload;
window.onload = function()
{ 
	if(typeof(existing) == "function")
	{
		  existing();
	}
	loadCapsChecker();
}
 
function loadCapsChecker()
{	
	capsClass = "capLocksCheck";
	capsNotice = "capsLockNotice";
 
	var inputs = document.getElementsByTagName('INPUT');
	var elements = new Array();
	for(var i=0; i<inputs.length; i++)
	{
		if(inputs[i].className.indexOf(capsClass) != -1)
		{
			elements[elements.length] = inputs[i];
		}
	}	
	for(var i=0; i<elements.length; i++)
	{
		if(document.addEventListener)
		{
			elements[i].addEventListener("keypress",checkCaps,"false");
		}
		else
		{
			elements[i].attachEvent("onkeypress",checkCaps);
		}
	}	
}
 
function checkCaps(e)
{
	var pushed = (e.charCode) ? e.charCode : e.keyCode;
	var shifted = false;		
	if(e.shiftKey)
	{
		shifted = e.shiftKey;
	}
	else if (e.modifiers)
	{
		shifted = !!(e.modifiers & 4);
	}			
	var upper = (pushed >= 65 && pushed <= 90);
	var lower = (pushed >= 97 && pushed <= 122);
	if((upper && !shifted) || (lower && shifted))
	{
		if(document.getElementById(capsNotice))
		{
			document.getElementById(capsNotice).style.display = 'block';
		}
		else
		{
			alert("Caps lock is on");
		}
	}
	else if((lower && !shifted) || (upper && shifted))
	{
		if(document.getElementById(capsNotice))
		{
			document.getElementById(capsNotice).style.display = 'none';
		}
	}
}

Advantages of this Script

  • Cross-browser functionality, tested in 7 modern browsers
  • Plug and play: no script modifications needed
  • Unobtrusive: your JS and HTML is separate and not interdependent
  • Rock Solid: never worry about error messages from missing elements or IDs
  • Conflict-free: does not break or overwrite any existing scripts