published: 18 May 2022
2 min read
How to detect if caps lock is on using 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+.
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:
<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:
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.
Are we missing something? Help us improve this article. Reach out to us.
How to detect if caps lock is on using 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+.
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:
<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:
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.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur