Tuesday, 24 May 2011

Detect key press with Jquery

To detect key presses with Jquery you can use the keydown method. The example below uses the "which" property to get the key code. Each character on the keyboard has a key code to correspond to the characters pressed.

$(function(){
 
 $(document).keydown(function(e)
 {
  console.log('The keycode is: ', e.which); 
 }); 
});

With the keycode obtained you can assign code to any key press on the keyboard. In the example below I have displayed a message when the A, B or C key is pressed. The keycode for A is 65, B is 66 and C is 67.

$(function(){

 $(document).keydown(function(e)
 {
  console.log('The keycode is: ', e.which);
  
  switch(e.which)
  {
   case 65:
    console.log('The A key is pressed');
   break;
   
   case 66:
    console.log('The B key is pressed');
   break;

   case 67:
    console.log('The C key is pressed');
   break;
  } 
 }); 

});

To make the code easily updatable and readable you can stored the keycodes in an Object. Below I have stored the A, B, and C keycodes in an object called KEY.

var KEY = {A:87, B:87, C:87};

$(function(){

 $(document).keydown(function(e)
 {
  console.log('The keycode is: ',  e.which);
  
  switch( e.which)
  {
   case KEY.A:
    console.log('The A key is pressed');
   break;
   
   case KEY.B:
    console.log('The B key is pressed');
   break;

   case KEY.C:
    console.log('The C key is pressed');
   break;
  } 
 }); 

});

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP