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

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

The Importance of Staying Active as a Software Developer

In today’s fast-paced digital world, developers often find themselves glued to their screens for extended periods. While this dedication is commendable, it comes with its own set of challenges.

Read more

JavaScript DOM Mastery: Top Interview Questions Explained

Mastering the Document Object Model (DOM) is crucial for any JavaScript developer. While many developers rely heavily on front-end frameworks, the underlying DOM concepts are still important.

Read more