The ability to detect the caps lock key can improve the usability of web applications — for example, a visitor entering a password could be warned if they have caps lock turned on. Unfortunately JavaScript has no mechanism to query whether caps lock is currently on or off. CapsLock.js works around this limitation by detecting the status of the key each time a letter is typed. In the example below, the light on the virtual key is updated as you type in the box.
Lock
Download CapsLock.js
Download one of the files below and either incorporate it into your code or serve it as a separate file.
File | Size | Description |
---|---|---|
CapsLock.js | 346 bytes | Minified version |
CapsLock.src.js | 1,476 bytes | Full version, with comments |
Using CapsLock.js
The current status of the caps lock key can be determined using the isOn
function, which returns true
if caps lock currently appears to be on and false
if it appears to be off:
1 2 3 4 5 6 |
|
Note that a change in the state of the caps lock key is only detected the next time a letter is typed.
The addListener
function allows a listener to be registered.
Whenever a change in the state of the caps lock key is detected the listener will be called with the value true
if caps lock is now on and false
if caps lock is now off.
For example:
1 2 3 4 5 |
|
Implementation
CapsLock.js works by listening for all key press events on the page and, if the key press corresponds to a letter being typed, comparing the case of the letter with the state of the shift key. On Windows, caps lock and shift interact as follows:
caps lock off | caps lock on | |
---|---|---|
shift off | lower case | upper case |
shift on | upper case | lower case |
On MacOS, the interaction is slightly different, as having both shift and caps lock on does not result in lower case letters:
caps lock off | caps lock on | |
---|---|---|
shift off | lower case | upper case |
shift on | upper case | upper case |
As a consequence, CapsLock.js cannot determine the state of the caps lock key on a Mac if shift is on. In practice this is not an issue, as shift is rarely used in combination with caps lock.