The need to verify and notify the user if the Caps Lock key is on is fairly common. It is particularly significant when constructing password inputs because users do not realize they are typing with their caps lock on. Let us see how to detect caps lock with JavaScript to do so.
There is a method called getmodifierState
that is available on KeyboardEvent
that we can use to do so. This can be accessed inside an event listener for a keyboard-related event:
document.querySelector('input[type=password]')
.addEventListener('keyup', (keyboardEvent) => {
const isCapsLockOn = keyboardEvent.getModifierState('CapsLock');
if (isCapsLockOn) {
// code for notifying the user goes here
}
});
JavaScriptAnd that piece of code tells us how to detect caps lock using JavaScript. We could have used the 'keydown'
method instead of using 'keyup'
if we wanted to. But keyup has better browser support, so we prefer using that instead. Let us know in the comments if you have any questions.
I recently switched completely to the Brave browser and have set ad blocking to aggressive…
I was preparing a slide deck for a hackathon and decided to put in a…
I have been using npx a lot lately, especially whenever I want to use a…
Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…
While working on a project, I wanted to do an integrity check of a file…
Popovers have been a problem that was typically solved by using a third-party solution. But…