How to Detect If Caps Lock is on With JavaScript
Javascript Tutorial

How to Detect If Caps Lock is on With JavaScript

1 min read

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.

About the Author

Matt Fay

Matt Fay

Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.

Discussion (Loading...)

Join the conversation

Join the Discussion

Sign in to share your thoughts and engage with the JavaScript Today community.

Loading comments...

Related Articles

Continue your learning journey with these related posts

Never Miss a JavaScript Update

Join our community of developers and receive insightful articles and coding tips every week.