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.

comments powered by Disqus

Related Posts

Unveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript

The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.

Read more

The Art of Data Visualization: Exploring D3.js

Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.

Read more

JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.

Read more