This website collects cookies to deliver better user experience
How to check or detect whether the CAPS LOCK is turned on or off using JavaScript?
How to check or detect whether the CAPS LOCK is turned on or off using JavaScript?
To check or detect whether the caps lock key is turned on or off, we can use the getModifierState() method on the input tag KeyBoardEvent and pass the string CapsLock to get the current state of the CapsLock key in JavaScript.
TL;DR
// get reference to the input tagconst myInput =document.getElementById("myInput");// listen for a keydown event in the myInputmyInput.addEventListener("keydown",(event)=>{// check if capslock is turned on or off// using the getModifierState() methodconst isCapsLockOn = event.getModifierState&& event.getModifierState("CapsLock");console.log(isCapsLockOn);// true});
To understand it better first let's make an HTML input and attach an id to reference it in JavaScript like this,
<!-- HTML input tag --><inputtype="text"id="myInput"/>
Now let's get a refernce to the myInput input in the JavaScript script using the getElementById() on the global document object like this,
// get refernce to the input tagconst myInput =document.getElementById("myInput");
Now to use the getModifierState() method, we have to listen for a KeyBoardEvent like keydown or keyup on the input field. Let's listen for the keydown Keyboard Event in our case.
So let's attach an event listener on the myInput using the addEventListener() method. It can be done like this,
// get refernce to the input tagconst myInput =document.getElementById("myInput");// listen for a keydown event in the myInputmyInput.addEventListener("keydown",()=>{// some cool stuff here!});
Now that we have attached the listener for the KeyBoardEvent, whenever the user presses or enter something in the input field a KeyBoardEvent will be passed an argument to the function in the addEventListener() method, so here we can use the getModifierState() method on the event object and pass the string CapsLock to check whether the Caps Lock button is currently turned on or off.
The getModifierState() method return a boolean value.
It can be done like this,
// get refernce to the input tagconst myInput =document.getElementById("myInput");// listen for a keydown event in the myInputmyInput.addEventListener("keydown",(event)=>{// check if capslock is turned on or offconst isCapsLockOn = event.getModifierState&& event.getModifierState("CapsLock");console.log(isCapsLockOn);// true});
Now you can see whether the caps lock is turned on or off when the user writes to the input tag.