How to detect the caps lock status in JavaScript

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
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources