Home >Web Front-end >JS Tutorial >How to Detect Arrow Key Presses in JavaScript?
Detecting Arrow Key Presses in JavaScript
Determining when arrow keys are pressed in JavaScript can be challenging because browsers interpret them differently due to default scrolling behavior.
Using onkeydown Event Listener
As mentioned in the issue, the onkeypress event does not capture arrow key presses. Instead, you need to use the onkeydown event listener. Modify your function as follows:
function checkKey(e) { var event = window.event ? window.event : e; if (event.type === "keydown") { console.log(event.keyCode); } }
Keycodes for Arrow Keys
The keycodes associated with the arrow keys are:
By using these keycodes within your condition, you can specifically detect arrow key presses:
function checkKey(e) { var event = window.event ? window.event : e; if (event.type === "keydown") { switch (event.keyCode) { case 37: // Left key pressed break; case 38: // Up key pressed break; case 39: // Right key pressed break; case 40: // Down key pressed break; } } }
The above is the detailed content of How to Detect Arrow Key Presses in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!