Detect Caps Lock with JavaScript

Published on

NaN

Caps Lock detection using getModifierState.

function checkCapsLock(event) {
  if (event.getModifierState) {
    return event.getModifierState('CapsLock');
  }
  return false; // Fallback if not supported
}

Example

function setupCapsLockDetection(inputElement, warningElement) {
  inputElement.addEventListener('keydown', function(event) {
    const isCapsLockOn = event.getModifierState('CapsLock');

    if (isCapsLockOn) {
      warningElement.textContent = '⚠️ Caps Lock is enabled';
      warningElement.style.display = 'block';
      warningElement.style.color = '#ff6b35';
    } else {
      warningElement.style.display = 'none';
    }
  });
}

const passwordField = document.querySelector('#password');
const warning = document.querySelector('#caps-warning');
setupCapsLockDetection(passwordField, warning);