JSFiddle - React, Tailwind, and code Playground
by Scott Kaye
HTML
<input type="password" id="t"><input type="password" id="t">
<div class="caps-lock-warning" style="display:none">Caps lock is on</div>
JavaScript
// Global caps lock watcher
// Tracks the status of the capslock key throughout the document
// Will notify the user if they enter a password field with caps lock enabled, and update automatically
$(function() {
var CAPS_LOCK_KEY = 20;
// Config
var $warning = $(".caps-lock-warning");
var $fields = $("input[type='password']");
function update() {
$warning.toggle(CapsLock.enabled);
}
// Exports
// "Private" field
var __e = undefined;
window.CapsLock = {
get enabled() { return __e; },
set enabled(e) {
__e = !!e;
if ($fields.is(":focus")) {
update();
}
$fields.one("input", update);
$fields.one("focus", update);
$fields.one("blur", function() { $warning.hide(); });
}
};
// Actual capslock detection
// Handle literal capslock key
$(document).keydown(function(e) {
if (e.which === CAPS_LOCK_KEY) {
// Flip value
CapsLock.enabled ^= 1;
}
});
// Handle every non-control (shift, alt, control, etc) keypress
// Disregard spaces and characters with no upper/lower variants
$(document).keypress(function(e) {
if (e.key.trim().length < 1) return;
var upper = e.key.toUpperCase();
var lower = e.key.toLowerCase();
var isSameCase = lower !== upper && upper === e.key;
var isShift = e.shiftKey;
CapsLock.enabled = !(isSameCase ^ !isShift);
});
});