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
.
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.
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);