Friday, March 02, 2007

Keyboard shortcuts with Javascript

{

Creating shortcuts on textboxes is none too difficult in Javascript, but (and don't get me wrong - I love Mr. Flanagan) the Rhino book is a bit abstruse. I was adding this functionality to my night project and pared it down to:

function handleKeyCommand(event){
var e = event window.event; // Key event object
var kCode = e.keyCode ¦¦ e.which; // What key was pressed
// I am trapping Ctrl+e (69) here
if(e.ctrlKey && (kCode == 69)){
var theButton = document.getElementById('actionButton');
theButton.click();
}
}

I'm calling that from the onKeyDown event of a TextArea the boring way; because I'm assigning it from the server side in ASP.NET, I have:

actionButton.Attributes.Add("onKeyDown", "handleKeyCommand(event);");

Which translates to onKeyDown="handleKeyCommand(event)"... the Web 2.0 kids would thumb this down since it's not an anonymous javacript function assigned after the page is loaded (I need to question that "inobtrusive javascript" ideology, but it's a post in the making), but this keeps it simple.

The main pitfall for me was in using onKeyDown rather than onKeyPress - the latter is more appropriate for obtaining ASCII related keyboard events, not special keys like shift, control, and so on. Another pitfall was browser compatibility; Flanagan also uses a nifty idiom when he allows the assignment of the event object occur with the operator. It returns the first true value and since an unassigned object returns false in javascript, writing the following assigns a reference to the event object based either on the parameter which would be passed by the browser (Firefox) or the built in window.event object (IE):

var e = event ¦¦ window.event; // Key event object

}

2 comments:

Aaron said...

So another way to get a form button clicked using the keyboard: accesskey.

<input type="submit" name="go" value="Click me" accesskey="e" />

In FF 2: use ALT-SHIFT-E
In pre FF 2: use ALT-E
In IE: use ALT-E

One difference is that in IE the button just gets focus while in FF the button is actually clicked, you can work around this by adding both an accesskey and an onfocus attribute:

<input type="submit" name="go" value="Click me" accesskey="e"
onfocus="document.form.submit()"
/>

Safari doesn't support accesskey's, but that's just because it sucks.

AJ

David Seruyange said...

Thanks Aaron, very good alternative with a smaller footprint.