Detecting CapsLock State (On/Off) with Javascript

It is sometimes required to detect whether the Caps Lock key is on or off. A major use of this is in login forms. If the Caps Lock is enabled, then the user may keep on entering incorrect passwords until he realizes this. In some cases, this may result in the user getting locked out (for example in internet banking) or solving a captcha.

All this could be prevented by informing the user that the Caps Lock key is turned on.

Demo

Note : Your CapsLock key is currently turned on

The get​Modifier​State() method to Detect State of Modifier Key

get​Modifier​State is a method available in the mouse and the keyboard event objects. This returns a true if the specified modifer key is currently pressed, and false otherwise.

This can be used to detect state of the Caps Lock key. Infact state of many other keys can be detected — "Alt", "Control", "NumLock", "Shift" etc.

document.querySelector("#password-field").addEventListener('keyup', function(e) {
	var caps_lock_on = e.getModifierState('CapsLock');

	if(caps_lock_on == true) 
		console.log('Caps Lock is turned on');
	else
		console.log('Caps Lock is turned off');
});

The get​Modifier​State method is only available on mouse and keyboard events. It even won't work on the focus event.

For best results you can listen to both the mouse and keyboard events for this.

document.querySelector("#password-field").addEventListener('keyup', checkCapsLock);
document.querySelector("#password-field").addEventListener('mousedown', checkCapsLock);

function checkCapsLock(e) {
	var caps_lock_on = e.getModifierState('CapsLock');

	if(caps_lock_on == true) 
		console.log('Caps Lock is turned on');
	else
		console.log('Caps Lock is turned off');
}
Loading Comments