Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get right, left, up and bottom arrow key value in jquery

I have used the below code, and whenever click the arrow key(left, right, up, down) i get the key value is "0". anyone can help on this?

 $(document).keypress(function (e) {

 alert("key value: " + e.which); 

  });

How to get (Up, Down, Right, Left) arrow key value when keypress.

like image 335
Bharathi Avatar asked Nov 21 '13 12:11

Bharathi


2 Answers

Use keydown insted of keypress

 $(document).keydown(function(event){    
    var key = event.which;                
            switch(key) {
              case 37:
                  // Key left.
                  break;
              case 38:
                  // Key up.
                  break;
              case 39:
                  // Key right.
                  break;
              case 40:
                  // Key down.
                  break;
        }   
  });
like image 119
Sarath Avatar answered Nov 01 '22 11:11

Sarath


In many browsers the keypress event doesn't recognise the arrow keys (nor keys like "shift", "del", "esc", etc. If you want to capture those key presses, you'll need to use keydown or keyup instead:

$(document).keydown(function (e) {

    alert("key value: " + e.which); 

});

JSFiddle demo.

As for the right, left, up and down arrow keys, those are:

left     37
up       38
right    39
down     40
like image 22
James Donnelly Avatar answered Nov 01 '22 11:11

James Donnelly