How to detect caps lock using JavaScript

Hello guys in this tutorial we will create Caps Lock Detector using html css and JavaScript

First we need to create two files index.html and style.css then we need to do code for it.

Step:1

Add below code inside index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Caps Lock detector</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="form-row">
    <form method="post">
      <div class="field">
        <input type="text" name="name" placeholder="Enter Text Here...">
        <span id="caps-message">Caps Lock is on!</span>
      </div>
    </form>
  </div>

  <script type="text/javascript">
    const CapsMessage = document.querySelector("#caps-message");
    window.addEventListener("keyup", event => {
      if (event.getModifierState("CapsLock")) {
        CapsMessage.style.display = "block";
      }else {
        CapsMessage.style.display = "none";
      }
    });
  </script>
</body>
</html>

Step:2

Then we need to add code for style.css which code i provide in below screen.

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@600&display=swap');
* {
  margin: 0;
  padding: 0;
  border: none;
  box-sizing: border-box;
  font-family: 'Open Sans', sans-serif;
}
body {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #121212;
}
form {
    width: 300px;
}
input {
    width: 100%;
    color: #fff;
    background: #000;
    outline: none;
    padding: 15px;
    border-radius: 2px;
    border: 1px solid #4766ff;
}
span#caps-message {
    color: #4766ff;
    text-align: center;
    width: 100%;
    margin-top: 15px;
    display: none;
}

Output:

Table of Contents

Leave a Comment