So, 24 Ways is here again this holiday season. If you don’t read 24 Ways, you really ought to. It’s an advent calendar for web geeks, touching on varying topics relating to development, design, typography, accessibility, and lots of stuff in between.
Day 4 was entitled, Capturing Caps Lock. Stuart Langridge presented a really smart way of capturing whether or not the Caps Lock key was on when entering a password. How handy?!
A lot of the JS development I’m doing nowadays is done via the Ext JS Framework. While Stuart’s code is quite usable, I found it hard to quickly scan the code. It’s not that I don’t understand it, it’s just not that readable. Since I’ve already got the Ext JS Framework on the pages I’d be using something like this Caps Lock checker, I figured why not just re-write it with some Ext functions. This helps in a lot of ways, such as being easier to scan through and less overall code. I think I cut his code in half. That being said, I’m also including the necessary Ext .js files.
Below is the code itself:
var CapsLock = {
init: function() {
var id = Ext.id();
this.alertBox = Ext.DomHelper.append(document.body,{
tag: 'div',
style: 'width: 8em',
children: [{
tag: 'div',
style: 'text-align: center; color: red;',
html: 'Caps Lock is on.',
id: id
}]
}, true);
Ext.fly(id).boxWrap();
this.alertBox.hide();
var pwds = Ext.query("INPUT[type='password']");
for(var i = 0; i < pwds.length; i++) {
Ext.get(pwds[i].id).on(
'keypress',
this.keypress.createDelegate(this,pwds[i],true),
this
);
}
},
keypress: function(e, el) {
var charCode = e.getCharCode();
if(
(e.shiftKey && charCode >= 97 && charCode <= 122) ||
(!e.shiftKey && charCode >= 65 && charCode <= 90)
){
this.showWarning(el);
} else {
this.hideWarning();
}
},
showWarning: function(el) {
var x = Ext.fly(el).getX();
var width = Ext.fly(el).getWidth();
var y = Ext.fly(el).getY();
this.alertBox.setXY([x + width + 6,y]);
this.alertBox.show();
},
hideWarning: function() {
this.alertBox.hide();
}
}
Ext.onReady(CapsLock.init, CapsLock, true);
You can see a working example here or download the Caps Lock script here.
Nice, I could use this sometimes.
Why don’t you write an own class for this by extending Ext.form.Field, this would make more sense to me.
If you need example code, you could have a look at my PasswordMeter
http://testcases.pagebakers.com/PasswordMeter/Ext.ux.PasswordMeter.js
Cheers!
[…] is the blog post about a rewrite of an existing caps lock notification function using the Ext JS Framework – give it a read if you use that JS framework in your sites already. I […]
appreciate it