Detect Caps Lock in JavaScript Easily

November, 4th 2024 2 min read

Detecting Caps Lock state is crucial for enhancing usability and reducing input errors, especially in password fields. Modern browsers provide reliable APIs for detecting modifier keys, but fallback techniques are important for cross‑browser robustness.

Understanding Keyboard Events and Modifier Keys

JavaScript exposes KeyboardEvent, which includes the getModifierState() method. It checks whether a modifier key (like CapsLock, Shift, or Control) is currently active.

Method 1: Using getModifierState()

This is the simplest and most reliable method in modern browsers.

js
document.addEventListener('keydown', event => {
  const isCapsLockOn = event.getModifierState('CapsLock');
  if (isCapsLockOn) {
    console.log('Caps Lock is ON');
  } else {
    console.log('Caps Lock is OFF');
  }
});

What getModifierState() Can Detect

It supports many modifier keys:

js
document.addEventListener('keydown', event => {
  if (event.getModifierState('Shift')) console.log('Shift active');
  if (event.getModifierState('Control')) console.log('Control active');
  if (event.getModifierState('Alt')) console.log('Alt active');
  if (event.getModifierState('NumLock')) console.log('NumLock active');
});

Method 2: Fallback Logic for Older Browsers

Older browsers may not support getModifierState. Use character comparison and the Shift key:

js
function detectCapsLock(event) {
  if (event.getModifierState) {
    return event.getModifierState('CapsLock');
  }

  const char = event.key;
  const shift = event.shiftKey;

  if (char >= 'A' && char <= 'Z' && !shift) return true;
  if (char >= 'a' && char <= 'z' && shift) return true;

  return false;
}

Practical Implementation: Reusable Detector Class

js
class CapsLockDetector {
  constructor(input) {
    this.input = input;
    this.warning = this.createWarning();
    this.init();
  }

  createWarning() {
    const el = document.createElement('div');
    el.textContent = 'Caps Lock is ON';
    el.style.cssText = `
      display: none;
      color: #c53030;
      font-size: 0.875rem;
      margin-top: 0.5rem;
    `;
    this.input.insertAdjacentElement('afterend', el);
    return el;
  }

  init() {
    this.input.addEventListener('keydown', e => this.update(e));
    this.input.addEventListener('focus', e => this.update(e));
    this.input.addEventListener('blur', () => {
      this.warning.style.display = 'none';
    });
  }

  update(event) {
    const caps = event.getModifierState('CapsLock');
    this.warning.style.display = caps ? 'block' : 'none';
  }
}

Usage

html
<input id="password" type="password" />
<script>
  new CapsLockDetector(document.getElementById('password'));
</script>

Best Practices

  • Improve UX: Only show warnings when the input is focused.
  • Accessibility: Add ARIA alerts for screen reader users.
  • Performance: Attach listeners only where necessary.
  • Cross‑browser reliability: Always include fallback logic.
  • Consider mobile: Caps Lock detection is inconsistent on mobile keyboards.

Common Mistakes to Avoid

  • Relying only on key codes.
  • Showing warnings too frequently or globally.
  • Ignoring international keyboard layouts.
  • Forgetting blur/focus handling.

Conclusion

Caps Lock detection enhances user experience and reduces form‑related errors. With getModifierState() plus fallback techniques, you can implement a reliable, accessible, and user‑friendly solution for any web application.