The question title says it all really. One caveat though: I did google it and the best solution I could find was to attach an onkeypress
event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lock must be on. This feels really dirty and just... wasteful - surely there's a better way than this??
views:
3413answers:
5In jquery:
$('some_element').keypress(function(e){
if(e.keyCode == 20){
//caps lock was pressed
}
});
This jquery plugin (code) implements the same idea in Rajesh's answer a bit more succinctly.
You can detect caps lock using "is letter uppercase and no shift pressed" using a keypress capture on the document. But then you better be sure that no other keypress handler pops the event bubble before it gets to the handler on the document.
document.onkeypress = function ( e ) {
e = e || window.event;
var s = String.fromCharCode( e.keyCode || e.which );
if ( s.toUpperCase() === s && !e.shiftKey ) { // incomplete: shift + caps MAY = lowercase
// alert('caps is on')
}
}
You could grab the event during the capturing phase in browsers that support that, but it seems somewhat pointless to as it won't work on all browsers.
I can't think of any other way of actually detecting caps lock status. The check is simple anyway and if non detectable characters were typed, well... then detecting wasn't necessary.
There was an article on 24 ways on this last year. Quite good, but lacks international character support (use toUpperCase()
to get around that).
In JQuery. This covers the event handling in Firefox and will check for both unexpected uppercase and lowercase characters. This presupposes an <input id="password" type="password" name="whatever"/>
element and a separate element with id 'capsLockWarning
' that has the warning we want to show (but is hidden otherwise).
$('#password').keypress(function(e) {
e = e || window.event;
// An empty field resets the visibility.
if(this.value === '') {
$('#capsLockWarning').hide();
return;
}
// We need alphabetic characters to make a match.
var character = String.fromCharCode(e.keyCode | e.which);
if(character.toUpperCase() === character.toLowerCase()) {
return;
}
// SHIFT doesn't usually give us a lowercase character. Check for this
// and for when we get a lowercase character when SHIFT is enabled.
if((e.shiftKey && character.toLowerCase() === character) ||
(!e.shiftKey && character.toUpperCase() === character)) {
$('#capsLockWarning').show();
} else {
$('#capsLockWarning').hide();
}
});