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?

ยท

2 min read

Originally Published Here ๐Ÿš€!

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 tag
const myInput = document.getElementById("myInput");

// listen for a keydown event in the myInput
myInput.addEventListener("keydown", (event) => {
  // check if capslock is turned on or off
  // using the getModifierState() method
  const 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 -->
<input type="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 tag
const 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 tag
const myInput = document.getElementById("myInput");

// listen for a keydown event in the myInput
myInput.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 tag
const myInput = document.getElementById("myInput");

// listen for a keydown event in the myInput
myInput.addEventListener("keydown", (event) => {
  // check if capslock is turned on or off
  const 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.

That's all ๐Ÿ˜ƒ!

See the above code live in JSBin

Feel free to share if you found this useful ๐Ÿ˜ƒ.