# How to detect if caps lock is on using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 30, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-detect-if-caps-lock-is-on

> Learn how to detect whether the caps lock is on or not in vanilla JavaScript.

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+.

```javascript
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:

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

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:

```javascript
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](https://attacomsian.com/blog/javascript-dom-add-an-event-handler) for the `keyup` event of the password field and display a hint when the caps lock is activated.
