getModifierState Detects CapsLock On Keydown

getModifierState('CapsLock') reports the physical lock state at keydown time, so password fields can surface a caps-lock hint without tracking keyup.

JavascriptForm Validation

Code

javascriptsnippet
17 lines
const password = document.querySelector('input[type="password"]');
const capsHint = document.querySelector('.caps-lock-hint');

password.addEventListener('keydown', (event) => {
  // getModifierState reports lock and modifier state at keydown time:
  // CapsLock, NumLock, ScrollLock, Shift, Alt, Control, Meta, OS.
  const capsLockOn = event.getModifierState('CapsLock');
  capsHint.hidden = !capsLockOn;
  console.log('CapsLock active while typing:', capsLockOn);
});

// Focus leaving the field must clear the hint, since CapsLock can change
// while the user is somewhere else entirely.
password.addEventListener('focusout', () => {
  capsHint.hidden = true;
  console.log('caps-lock hint cleared');
});

What this snippet actually does — getModifierState Detects CapsLock On Keydown

Top-level bindings password, capsHint hold the demo state — nothing sits inside a function scope.

Caveats

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.
  • A browser is the runtime here: document are not available in Node.

Using it

The run prints CapsLock active while typing:, caps-lock hint cleared — each prefix names the step that produced it.

Key statements

password.addEventListener('focusout', () => {
  capsHint.hidden = true;
  console.log('caps-lock hint cleared');
});

Interactive Tools for This Topic

FAQ

Does getModifierState Detects CapsLock On Keydown run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.