Home Kate Morley on Mastodon

Detecting caps lock in JavaScript

Detecting the state of the caps lock key can improve the usability of web applications. For example, a visitor entering a password can be warned if they have caps lock turned on, as in this live demonstration:

Although there is no browser API to query the current state of the caps lock key, its state can be detected each time a key is pressed by using the getModifierState method of the keyboard event object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
window.addEventListener('keydown', detectCapsLock)
window.addEventListener('keyup', detectCapsLock)

function detectCapsLock(e) {
  if (e.getModifierState('CapsLock')) {
    // caps lock is on
  } else {
    // caps lock is off
  }
}

We need to listen for both keydown and keyup events so that we can detect presses of the cap lock key itself. Usually browsers dispatch a keydown event when a key is pressed down and a keyup event when it’s released, but for the caps lock key only one of these events is dispatched on each press.

All browsers dispatch only a keydown event when the caps lock key is pressed to turn caps lock on. Firefox also dispatches only a keydown event when the caps lock key is pressed to turn caps lock off, but Chrome, Safari, and Edge dispatch only a keyup event instead (in effect, they act as if caps lock is another shift key that’s being pressed down for the duration of caps lock being turned on).