patternjavascriptMinor
Checking when capslock is turned on
Viewed 0 times
checkingturnedcapslockwhen
Problem
I've written this JQuery program for checking whenever caps lock is turned on.
$("input[type='password']").keypress(function(e) {
var kc = e.which; //get keycode
var isUp = (kc >= 65 && kc = 97 && kc <= 122) ? true : false; // lowercase
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ( (isUp && !isShift) || (isLow && isShift) ) {
capLock(); // alerts "CAPSLOCK is ON"
}
});
function capLock() {
alert('CAPSLOCK is ON');
}Solution
Turning my comment on your question into an answer:
On a Mac, when the Caps Lock key is engaged, the Shift key doesn't change the case to lower. So in the event that the Caps Lock key has already been engaged, before your page even loads, this code won't work as intended. I believe this jQuery plugin has already solved this problem - github.com/nosilleg/capslockstate-jquery-plugin
As for your code itself:
to:
because (kc >= 65 && kc
to:
The interesting thing about the statement above is that it takes advantage of a mechanism called short-circuit evaluation that boolean operators, like OR (
Basically, in an OR statement, if the first expression evaluates to
Similarly for an AND statement, if the first expression evaluates to
On a Mac, when the Caps Lock key is engaged, the Shift key doesn't change the case to lower. So in the event that the Caps Lock key has already been engaged, before your page even loads, this code won't work as intended. I believe this jQuery plugin has already solved this problem - github.com/nosilleg/capslockstate-jquery-plugin
As for your code itself:
- I like that you've got named variables, that makes the final
ifstatement super easy to read. You could name the event variable as such too, so it's clearer whatecontains.
- You can refactor this
var isUp = (kc >= 65 && kc
to:
var isUp = (kc >= 65 && kc <= 90) // uppercasebecause (kc >= 65 && kc
to:
var isShift = ( e.shiftKey ) || (kc == 16);The interesting thing about the statement above is that it takes advantage of a mechanism called short-circuit evaluation that boolean operators, like OR (
||) and AND (&&), use.Basically, in an OR statement, if the first expression evaluates to
true, the second expression is never evaluated, because true || anything will always evaluate to true.Similarly for an AND statement, if the first expression evaluates to
false, the second expression is never evaluated, because false && anything will always evaluate to false.Code Snippets
var isUp = (kc >= 65 && kc <= 90) // uppercasevar isShift = ( e.shiftKey ) || (kc == 16);Context
StackExchange Code Review Q#93168, answer score: 7
Revisions (0)
No revisions yet.