JavaScript

How to detect caps lock with JavaScript

Advertisements

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
    }
});
JavaScript

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

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria

Recent Posts

Fixing cookies are blocked for a website with shields down on Brave

I recently switched completely to the Brave browser and have set ad blocking to aggressive…

4 months ago

Generating a QR code using Node.js

I was preparing a slide deck for a hackathon and decided to put in a…

5 months ago

How to clear the global npx cache

I have been using npx a lot lately, especially whenever I want to use a…

5 months ago

Copy/Pasting output from the terminal

Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…

6 months ago

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

7 months ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

7 months ago
Advertisements