jQuery: Catch Keyboard Events

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

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:

$(document).keypress(function (eh){ 
  alert("Keypress: The key is: "+getKey(eh)); 
$(document).keyup(function (eh){
  alert("Keyup: The key is: "+getKey(eh));

$(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.

By Alaa Badran

Front-End and Web developer


Leave a Reply to Rapidshare SE Cancel reply

Your email address will not be published. Required fields are marked *