Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting arrow key presses in JavaScript

How do I detect when one of the arrow keys are pressed? I used this to find out:

function checkKey(e) {     var event = window.event ? window.event : e;     console.log(event.keyCode) } 

Though it worked for every other key, it didn't for arrow keys (maybe because the browser is supposed to scroll on these keys by default).

like image 399
mihsathe Avatar asked Apr 08 '11 15:04

mihsathe


People also ask

How can you tell if an arrow key is pressed?

To detect the arrow key when it is pressed, use onkeydown in JavaScript. The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.

How do you detect if a key is being pressed in JavaScript?

Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

How do you tell which arrow key is which?

Alternatively referred to as cursor keys, direction keys, and navigation keys, the arrow keys are usually located between the standard section and the numeric pad on computer keyboards. It is made up of four keys: the left arrow (back arrow), up arrow, down arrow, and the right arrow (forward arrow).

What is arrow keys keyCode?

Arrow keys are only triggered by onkeydown , not onkeypress . The keycodes are: left = 37. up = 38. right = 39.


1 Answers

Arrow keys are only triggered by onkeydown, not onkeypress.

The keycodes are:

  • left = 37
  • up = 38
  • right = 39
  • down = 40
like image 192
Nobody Avatar answered Oct 18 '22 21:10

Nobody