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

The Great JavaScript Debate: To Semicolon or Not?

Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.

Read more

Hacktoberfest 2024: Get a Free JavaScript Today Sticker

October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.

Read more

Creating a Real Time Chat Application with React, Node, and TailwindCSS

In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.

Read more