Detect caps lock on/off using JavaScript

640 views Asked by At

I can be trying the registration Form and the detection caps lock is on or off showing a warning under confirm password (WARNING! caps lock is on/WARNING! caps lock is off)

Wwhen I press capslock (caps lock is on) then shows a warning completely but when I press capslock (caps lock is off) then not show a stop warning

window.addEventListener('keyup', event => {
  var isCaps = event.getModifierState('CapsLock');
  if (isCaps) {
    //true
    document.getElementById('alert').innerText = " WARNING! caps lock is on";
  } else {
    //false
    document.getElementById('alert').innerText = "";
  }
})
My HTML code looks like this:

<form action="#" method="post" keyup="validate()">
  <h1>login Form</h1>
  <div>
    <label for="username">username</label>
    <input id="username" type="text" name="username">

  </div>
  <div>
    <label for="password">password</label>
    <input type="password" name="confirm_password" id="password">

  </div>
  <div>
    <label>confirm password</label>
    <input type="password" name="confirm_password" id="confirm_password" onkeyup="check(this)">
    <br>
    <error id="alert"> </error>

  </div>
  <div>
    <button type="button">submit</button>

  </div>
</form>

1

There are 1 answers

4
neria work On

hi change the event to keyDown

window.addEventListener("keydown", (event) => {
  let isCaps = event.getModifierState("CapsLock");
  console.log(isCaps);
  if (!isCaps) {
    document.getElementById("alert").innerText = "";
  } else {
    //true
    document.getElementById("alert").innerText = " WARNING! caps lock is on";
  }
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="app.js" defer></script>
    <title>Document</title>
  </head>
  <body>
    <p id="alert"></p>
  </body>
</html>