08.3.2009

jQuery: Catch Keyboard Events

Bookmark and Share
Add to DZone

Link: http://www.freelancer-id.com/files/jkey/

Lot of jQuery projects relies on keyboard/mouse event like pressing "p" for previous and "n" for next also using the arrows.

Because this is important, I have managed a code to get the keyboard character on 3 events:
- Keypress
- Keyup
- Keydown

I have created a function to return the key as below:

function getKey(key){
if ( key == null ) {
keycode = event.keyCode;
// To Mozilla
} else {
keycode = key.keyCode;
}
// Return the key in lower case form
return String.fromCharCode(keycode).toLowerCase();
}

Now let's use the events:

/*Keypress*/
$(document).keypress(function (eh){
alert("Keypress: The key is: "+getKey(eh));
});

/*Keyup*/
$(document).keyup(function (eh){
alert("Keyup: The key is: "+getKey(eh));
});

/*keydown*/
$(document).keydown(function (eh){
alert("Keydown: The key is: "+getKey(eh));
});

To see an exaple of this code, please check the demo below:
jKey demo

Have fun.

5 comments

Comment from: Rapidshare SE [Visitor] · http://rapidpedia.com
It is a very nice idea. You are genious!
03/21/10 @ 19:37
Comment from: ambarcatiuni [Visitor] · http://www.marina-braila.ro
Awesome, I'm using it on a barci site.
Thank you!
05/05/10 @ 00:37
Comment from: Wahyu Primadi [Visitor] · http://www.wahyuprimadi.co.cc
nice... but functin getKey() not in jQuery style...
05/29/10 @ 13:08
Comment from: alex [Visitor] · http://watchanimeonline.us/
well i want to catch the f1,f2...f12 buttons events in jquery how it will be done
08/07/10 @ 12:27
Comment from: James [Visitor] · http://rapidok.com
Thanks for comprehensive explanations. Sometimes it's quite difficult to find a lot of relevant information concerning jQuery implementations.

Kindest regards.
08/27/10 @ 14:05

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)
Free Blog Themes / Templates