How To Detect Caps Lock In JavaScript

First, let us look at the HTML code,

<!DOCTYPE html>
<html>
<style>
#text {display:none;color:red}
</style>
<body>
     <h3>Detect Caps Lock</h3>
         <p>Press the "Caps Lock" key inside the input field to trigger the function.</p>
             <input id="myInput" value="Some text..">
         <p id="text">WARNING! Caps lock is ON.</p>
</body>
</html>

Next, we will look at the Javascript code,

<script>
var input = document.getElementById("myInput");
var text = document.getElementById("text");
input.addEventListener("keyup", function(event) {
    if (event.getModifierState("CapsLock")) {
        text.style.display = "block";
    } else {
        text.style.display = "none"
    }
});
</script>

All the code(HTML and JavaScript is below),

<!DOCTYPE html>
<html>
<style>
#text {display:none;color:red}
</style>
<body>

<h3>Recognise Caps Lock</h3>
<p>Press the "Caps Lock" key inside the input field to trigger the function.</p>

<input id="myInput" value="Some text..">
<p id="text">WARNING! Caps lock is ON.</p>

<script>
var input = document.getElementById("myInput");
var text = document.getElementById("text");
input.addEventListener("keyup", function(event) {
    if (event.getModifierState("CapsLock")) {
        text.style.display = "block";
    } else {
        text.style.display = "none"
    }
});
</script>

</body>
</html>

Output Sample

How To Detect Caps Lock In JavaScript