Keywatcher.js - capture key presses (Mootools)
Here’s a nice little extension I found on the mootools forums. It let’s you assign an action to any element when the element has focused and the user clicks a key. I haven’t played around with it yet, but it’s super small and looks useful for form inputs and whatnot. Credit goes to BlackMac.
/*
Script: keywatcher.js
Here be Dragons
Dependencies:
<Moo.js>, <Element.js>
Author:
Stefan Lange-Hegermann, <http://www.blackmac.de/>
License:
MIT-style license.
Credits:
This only works with mootools
*/
Element.implement({
/*
Property: attachAllKeys
makes the function passed listen to all keydown events
Arguments:
callback - the function that gets called when a key is pressed
KeyCode is passed as the first parameter
Example:
>$E('html').attachAllKeys(keyListener);
*/
attachAllKeys: function (callback) {
this.callback=callback;
if (!this.keyEventAdded) {
this.onkeydown=this.keyDown;
}
this.keyEventAdded=true;
},
/*
Property: attachKeys
makes certain functions from an array listen to certain keys
Arguments:
keylist - the function that gets called when a key is pressed
KeyCode is passed as the first parameter
Example:
>$E('html').attachKeys({54:functionOne, 55:functionTwo});
*/
attachKeys: function (keylist) {
if (!this.keyFunctions)
this.keyFunctions={};
Object.extend(this.keyFunctions, keylist);
if (!this.keyEventAdded) {
this.onkeydown=this.keyDown;
}
this.keyEventAdded=true;
return this;
},
/*
Property: attachKeys
makes a certain function listen to a certain key
Arguments:
keyCode - the key code or the keys letter as a string
callback - the function to call, when the key is hit
Example:
>$E('html').attachKey(54, functionOne);
*/
attachKey: function (keyCode, callback) {
var tmplist=[];
if (typeof(keyCode)=="string") {
keyCode = keyCode.toUpperCase().charCodeAt(0);
}
tmplist[keyCode]=callback;
this.attachKeys (tmplist);
return this;
},
// internal
keyDown: function (event) {
if (event.target == this) {
if (this.keyFunctions) {
if (this.keyFunctions[event.keyCode]) {
return this.keyFunctions[event.keyCode](event.keyCode);
}
}
if (this.callback) {
return this.callback(event.keyCode);
}
}
return true;
}
})

November 26th, 2006 at 6:13 am
Hi, very nice script! Is it possible to submit a form by pressing the key combination “Ctrl + S”?
ciao André
November 26th, 2006 at 10:51 am
Yes, it is possible, but this script (which I didn’t write) won’t let you do it. My comment to the author of this script (on the Mootools forum) was that you should be able to define key intersections. It’s possible to capture ctrl+click, +key, etc.
November 27th, 2006 at 2:03 pm
I will add that functionality this week. Maybe even tomorrow.
April 2nd, 2007 at 11:14 pm
how can i capture alter+enter key combination….
April 4th, 2007 at 9:24 am
This is now somewhat deprecated. If you’re using Mootools, see:
http://docs.mootools.net/files/Native/Event-js.html#Event