To detect if the caps lock is on in JavaScript, you can use the getModifierState() method of the KeyboardEvent event object.

The KeyboardEvent can be used to detect the state of several keys, including caps lock on modern browsers and IE9+.

const isCapsLock = event.getModifierState(modifier);

The getModifierState() method returns true if the specified modifier key was pressed, or activated.

Let us you have got the following password field and want to alert the user when the caps lock is activated:

    <input type="password" name="password" id="password" placeholder="Enter password">
    <span id="hint"></span>

The following example demonstrates how you can show a warning message to the user if they turn on the caps lock while typing the password:

const password = document.querySelector('#password');
const hint = document.querySelector('#hint');

// Lisen for `keyup` event
password.addEventListener('keyup', (e) => {
    if (e.getModifierState('CapsLock')) {
        hint.textContent = 'Caps lock is on';
    } else {
        hint.textContent = '';

In the above example, we listen for the keyup event of the password field and display a hint when the caps lock is activated.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: