How to Detect If Caps Lock is on With JavaScript

One of the most frustrating things to do is enter a wrong password, having to type your email and password for a second time. It’s such a relief when we’re alerted that caps lock is on – we know to stop what we’re doing and reenter our password immediately.

This article will show you how to implement this feature on your websites.

Detect Caps Lock Code Snippets

We’re going to start with an HTML input tag, as well as a div to display the warning message:

<input
  type="password"
  name="password"
  id="password"
  placeholder="Enter a password"
/>
<div class="warning"></div>

Let’s also style the warning message for the fun of it:

.warning {
  color: red;
}

Now to add the functionality:

const password = document.querySelector("#password");
const warning = document.querySelector(".warning");

password.addEventListener("keyup", function (e) {
  if (e.getModifierState("CapsLock")) {
    warning.innerHTML = "<p>Caps lock is on</p>";
  } else {
    warning.innerHTML = "";
  }
});

We declare two variables, password, and warning. password is declared to select the input tag, and warning will be used to display the message.

The first step is to attach an event listener to the input element (password), which will watch for keyup events. If a keyup event is detected, we’re going to use the .getModifierState method to detect if caps lock is on or not. If it is, we’re going to attach some HTML to the warning message: "<p>Caps lock is on</p>", else, if it’s not on, the message will be set to an empty string.

Related Posts

The Importance of Pi in Mathematics and Pi Day: Exploring with JavaScript

Pi (π) is one of the most famous and important constants in mathematics. It has fascinated mathematicians, scientists, and students for centuries due to its mysterious and infinite nature.

Read more

Finding Free and Discounted Programming Books

As an avid reader, I’m always looking for places to find my next book. If they’re free, even better. Although it’s not always so easy finding them, there are plenty available online.

Read more

Getting Started with Google Cloud

In this article, we’re going to be taking a first look at Google Cloud, a leading player in the world of cloud computing, offers services and tools designed to drive innovation and ease operations.

Read more