user3655060
user3655060

Reputation: 11

Click event on the keyboard: up, down, left, right

I need an event that gives one click right, up, down or left. I want that when a condition is met (if) he give a click on the button I choose, below is an example in which should fit:

if (gesture.left) { The click event in the left direction button keypad } Else if (gesture.right) { Click the event in the right direction button keypad }

Do not want to detect which key was pressed, only one condition that after he click button that I want.

Upvotes: 1

Views: 6112

Answers (3)

A H K
A H K

Reputation: 1750

<form>
 <input id="target" type="text" value="Hello there">
</form>

<script>
  $("#target").keydown(function(e){
   if (e.keyCode == 37) { 
     alert( "left pressed" );
     return false;
   }else  if (e.keyCode == 39) { 
     alert( "right key pressed" );
     return false;
   }else  if (e.keyCode == 38) { 
     alert( "Up key pressed" );
     return false;
   }else  if (e.keyCode == 40) { 
     alert( "Down key pressed" );
     return false;
    }
   });
</script>

Upvotes: 0

A H K
A H K

Reputation: 1750

arrow keys are only triggered by onkeydown, not onkeypress

keycodes are:

  • left = 37
  • up = 38
  • right = 39
  • down = 40

http://jsfiddle.net/ahmadhasankhan/qqqpf/2/

Upvotes: 5

Manwal
Manwal

Reputation: 23836

Try this code:

$(function(){
    $('html').keydown(function(e){
        if(e.keyCode == 37) { // left
          }
          else if(e.keyCode == 39) { // right
          }
        else if(e.keyCode == 38) { // up
          }
        else if(e.keyCode == 40) { // down
          }
    });
});

Demo

You can also use which instead of keyCode, Like following:

$(function(){
        $('html').keydown(function(e){
            if(e.which== 37) { // left
              }
              else if(e.which == 39) { // right
              }
            else if(e.which == 38) { // up
              }
            else if(e.which == 40) { // down
              }
        });
    });

Upvotes: 0

Related Questions