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.
Code
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:
documentare 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.