Skip to content

Instantly share code, notes, and snippets.

@rigalpatel001
Created August 17, 2024 09:35
Show Gist options
  • Save rigalpatel001/e627cebce114edffafb86aa80b5d30f6 to your computer and use it in GitHub Desktop.
Save rigalpatel001/e627cebce114edffafb86aa80b5d30f6 to your computer and use it in GitHub Desktop.
Top 3 Ways to Detect Caps Lock in Your Web App
When users enter passwords or other sensitive information in a web application, it's crucial to provide them with the best possible experience. One common issue is the accidental activation of Caps Lock, which can lead to failed login attempts and user frustration. In this blog, we’ll explore simple ways to detect Caps Lock using JavaScript to improve your application's usability and security.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Caps Lock Detection Test</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
.caps-warning {
color: red;
font-weight: bold;
display: none;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Test Caps Lock Detection</h1>
<p>Type in the input field below and see if Caps Lock is detected:</p>
<input
type="password"
id="passwordInput"
placeholder="Enter your password"
/>
<div id="capsWarning" class="caps-warning">Caps Lock is ON!</div>
<script>
const passwordInput = document.getElementById("passwordInput");
const capsWarning = document.getElementById("capsWarning");
// Method 1: Using keydown and keyup events with getModifierState
passwordInput.addEventListener("keydown", function (event) {
if (event.getModifierState("CapsLock")) {
capsWarning.style.display = "block";
} else {
capsWarning.style.display = "none";
}
});
// Method 2: Using keypress event and checking event.which value
passwordInput.addEventListener("keypress", function (event) {
let charCode = event.which || event.keyCode;
let character = String.fromCharCode(charCode);
if (
character.toUpperCase() === character &&
character.toLowerCase() !== character &&
!event.shiftKey
) {
capsWarning.style.display = "block";
} else {
capsWarning.style.display = "none";
}
});
// Method 3: Combining keydown, keyup, and keypress events
let isCapsLockOn = false;
passwordInput.addEventListener("keydown", function (event) {
if (event.getModifierState("CapsLock")) {
isCapsLockOn = true;
capsWarning.style.display = "block";
} else {
isCapsLockOn = false;
capsWarning.style.display = "none";
}
});
passwordInput.addEventListener("keypress", function (event) {
let charCode = event.which || event.keyCode;
let character = String.fromCharCode(charCode);
if (
character.toUpperCase() === character &&
character.toLowerCase() !== character &&
!event.shiftKey
) {
if (!isCapsLockOn) {
isCapsLockOn = true;
capsWarning.style.display = "block";
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment