Hello Developers, In this blog, we will learn how we can detect caps lock is turned on or off in javascript
Let’s get started
First of all, create a new HTML file then write the above code into your HTML file
<!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"> <title>Document</title> </head> <body> <input type="text" id="myInput"> <p id="text">Warning! Caps lock is ON.</p> </body> </html>
Paste the above code into your CSS file
input { padding: 10px; font-weight: 500; } #text { color: red; display: none; }
Now paste the above code in your Javascript file
var input = document.getElementById("myInput"); var text = document.getElementById("text"); input.addEventListener("keyup", function (event) { if (event.getModifierState("CapsLock")) { // This will return true if your caps-lock is on text.style.display = "block"; } else { text.style.display = "none" } });
Demo: