How can I detect the Caps Lock state on page load (i.e. not on keyboard) using JavaScript?
So I was looking into Caps Lock detection solutions for a form using JavaScript / jQuery. There is a huge thread on stackoverflow offering many solutions. But the only problem is that they don't check if the Caps Lock is pressed by itself. They determine if a capital letter has been entered and that the shift key has not been pressed. The downside to this is that my Caps Lock alert won't turn on / off until the user starts typing a form, which is hardly optimal. Here is my code.
document.onkeypress = function(e){
e = e || window.event;
var s = String.fromCharCode(e.keyCode || e.which);
if (s.toUpperCase() === s && !e shiftKey) {
capsWarning.style.visibility = 'visible';
} else {
capsWarning.style.visibility = 'hidden';
}
}
Is there a better way so that I can trigger a lock message using JavaScript when I press the Caps Lock key? That is, don't delay turning off the message until after I start typing?
Preferably, I would prefer a pure JavaScript to JQuery solution. Although, if you think jQuery is really really really good, please tell me why and I could pressure my colleague to include it here; o
source to share
I used this piece of code and tried to send an event. getModifierState
MSDN , MDN will not return other than false. In this case, in fact, you send the character as it is - "a" or "A". It will be hardcoded anyway.
getModifierState
will return true only in case of a real key press.
But there is automatic CapsLock detection in IE 11 (for <input type="password" />
)
var eventType = "keypress";
window.addEventListener ( eventType, function(e){
var msg = "Key Pressed: " + String.fromCharCode(e.charCode) + "\n" + "charCode: " + e.charCode + "\n" + e.getModifierState ( "CapsLock" );
console.log ( msg );
}, false );
function simulateKeyEvent() {
var evt = document.createEvent("KeyboardEvent");
var initMethod = typeof evt.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
evt[initMethod](
"keypress", // type,
true, // bubbles,
true, // cancelable,
window, // viewArg,
0, // ctrlKeyArg,
0, // altKeyArg,
0, // shiftKeyArg,
0, // metaKeyArg,
/* lower a */ 97, // keyCodeArg,
/* lower a */ 97 // charCodeArg
);
window.dispatchEvent(evt);
}
simulateKeyEvent();
source to share
I tested this in chrome and it worked by putting this javascript in the tag
function loadcaps ( e ) {
e = e || window.event;
var s = String.fromCharCode( e.keyCode || e.which );
if ( s.toUpperCase() === s && !e.shiftKey ) {
capsWarning.style.visibility = 'visible';
} else {
capsWarning.style.visibility = 'hidden';
}
}
}
and put this on your tag
<body onload="loadcaps()">
let me know if it works for you.
source to share