Determine if caps lock is on with MooTools
This is a quick idea I came up with. We extend the Event native like this:
Event.implement({ hasCapsLock: function(){ return ((this.code > 64 && this.code < 91 && !this.shift) || (this.code > 96 && this.code < 123 && this.shift)); } });
And then access the method from a keypress event:
$('test').addEvent('keypress', function(event){ if (event.hasCapsLock()){ // do something } });
The only drawback is that it relies on sniffing alphabet characters and whether the shift key was pressed. This means that if the user presses the caps lock key, you won’t know it until another character is inserted.
-
Yes. You are correct. I jumped past the idea. Ok, what about adding an on focus event to the input field to make any typed string lowercase. Thereby bypassing the caps lock in case it is on. However, there would need to be a check for when the shift key is pressed to allow for uppercase letters. No alerts would be necessary. Although, this would leave out those who like to use the caps lock for uppercase letters. What do you think? Flawed logic or perhaps this could lead to some way of detecting the caps lock? I attempted to write a small snippet of code but not sure if it would be useful. Thanks for the above code anyhow Guillermo. Rock on!
-
Hi Guillermo:
Try this to eliminate the key sniffing.Event.Keys.capslock = 20;
$(‘test’).addEvent(‘keydown’, function(event){
if (event.key == “capslock”)
alert(“You pressed capslock.”);
});I tested on the following browsers via Mootools 1.2.1/Vista box:
Firefox 3.0.8
Opera 10.0 alpha
Safari 3.2.2
Chrome
1.0.154.48
Flock 2.0
Maxthon 2.1.4
Wyzo 3.0.1
Internet Empire 7.0/8.0
Internet Sux (don’t care)All seem to work. Any thoughts?
Hi Guillermo,
Nice idea. Thanks for sharing.
Here is a jQuery Plugin inspired by your tip (french article) :
http://blog.jaysalvat.com/articles/detecter-et-indiquer-activation-touche-capslock-avec-jquery.php