Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to detect the caps lock status in JavaScript

Programming Bytes

You can retrive the current state of the specified modifier using the KeyboardEvent.getModifierState() method.

The KeyboardEvent.getModifierState() method returns true if a modifier is active, otherwise, it returns false.

The modifier key for detecting Caps lock is CapsLock. We can pass this to the getModifierState function and detect the state of the CapsLock.

Check if caps lock is on or off

document.addEventListener('keyup', (e) => {
     if (e.getModifierState('CapsLock')) {
         cosole.log("Caps Lock is on");
     } else {
         cosole.log("Caps Lock is off");
     }
 });

You can also bind the event listener to the input element and give info to the user about the caps lock status.

Detect caps lock change

The browser treats caps lock on as keydown and caps lock off as keyup, so we need to bind both keydown and keyup to detect a change in caps lock. This is shown below:

function testCapsLock(event) {
    if(event.code === "CapsLock"){
        let isCapsLockOn = event.getModifierState("CapsLock");
        if(isCapsLockOn) {
            console.log("Caps Lock turned on");
        } else {
            console.log("Caps Lock turned off");
        }
    }
}

document.addEventListener("keydown", testCapsLock);
document.addEventListener("keyup", testCapsLock);

Code

Console

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring