Detecting Arrow Key Presses in JavaScript

Detecting arrow key presses in JavaScript

Arrow keys are only triggered by onkeydown, not onkeypress.

The keycodes are:

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

HandleKeyPress not recognising down arrow

event.which will give you the numeric value of the key.

event.key and event.code will give you a string value.

Try this tool: http://keycode.info

if (event.key === 'ArrowDown') {
console.log('Down arrow key fired');
}

As @devserkan mentioned you should use onKeyDown instead of onKeyPress.

The keydown event is fired when a key is pressed down. Unlike the keypress event, the keydown event is fired for keys that produce a character value and for keys that do not produce a character value.

Detecting Arrow key press in IE via javascript/jQuery

From the jQuery keypress documentation (the last paragraph of the introductory text):

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 97 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

It even literally mentions about the arrow keys ;) Thus, you really need to hook on either the keydown or keyup events. Here's an SSCCE with keydown, just copy'n'paste'n'run it. No, you don't need to do a browser-compatible check on the event, this works in all browsers from IE6 up to with Firefox.

<!doctype html>
<html lang="en">
<head>
<title>SO question 2217553</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).keydown(function(event) {
switch (event.keyCode) {
case 37: alert('left'); break;
case 38: alert('up'); break;
case 39: alert('right'); break;
case 40: alert('down'); break;
}
});
</script>
</head>
<body>
<p>Press one of the arrow keys.</p>
</body>
</html>

How to detect arrow keys in a Javascript game?

So, the biggest issue is that you were never calling your move() function. I added a call to the move() function to your keydown event and then continually console logged everything that was happening until I figured out what was wrong.

Here is my edited code ( I left the console.logs in to show you how I debugged it). It shows the paddle moving and in the correct direction.

You may also have an issue with the delayed paddle movement when holding down a key because it takes a second to register that the key is being held down instead of pressed. I've attached a JS eventhandler reference to help you out in finding a way around that.

You also need to click the page to bring it in focus.

var canvas;var canvasContext;var ballX = 50;var ballSpeedX = 10;var ballY = 50;var ballSpeedY = 5;var ym = 10; // the movement of y axisvar keys = new Array();
var player1Score = 0;var player2Score = 0;const WinningScore = 11115;
var showingWinScreen = false;
var paddle1 = 350;var paddle2 = 350;const paddleHeight = 100;const paddleThickness = 10;

function PausePressed(evt) { if (showingWinScreen) { player1Score = 0; player2Score = 0; showingWinScreen = false;
}}

window.onload = function() { canvas = document.getElementById('Mycanvas'); canvasContext = canvas.getContext('2d'); window.addEventListener('keydown', doKeyDown, true); window.addEventListener('keyup', doKeyUp, true);
var framesPerSecond = 60; setInterval(function() { moveEverything(); drawEverything(); }, 1000 / framesPerSecond);
}
function ballReset() { if (player1Score >= WinningScore || player2Score >= WinningScore) {
showingWinScreen = true; }
ballX = canvas.width / 3; ballY = canvas.height / 3; ballSpeedX = -ballSpeedX}
function doKeyDown(evt) { keys[evt.keyCode] = true; console.log("current keyCode:",evt.keyCode) move() evt.preventDefault(); // Prevents the page to scroll up/down while pressing arrow keys}
function doKeyUp(evt) { console.log("'key up' event fired") console.log(`keyCode: ${evt.keyCode} keys: ${keys}`) console.log(" 'key[evt.keyCode]' before:", keys[evt.keyCode]) keys[evt.keyCode] = false; console.log(" 'key[evt.keyCode]' after:", keys[evt.keyCode]) console.log(`keyCode: ${evt.keyCode} keys: ${keys}`)}
function move() { console.log("Entered move function") if (38 in keys && keys[38]) { //up console.log("entered '38 in keys'. UP ") console.log("paddle1 before -= :", paddle1) paddle1 -= ym; console.log("paddle1 after -= :", paddle1) } else if (40 in keys && keys[40]) { //down console.log("entered '40 in keys'. DOWN ") console.log("paddle1 before += :", paddle1) paddle1 += ym; console.log("paddle1 after += :", paddle1) }}
function computerMovement() { var paddle2Center = paddle2 + (paddleHeight / 2); if (paddle2Center < ballY - 30) { paddle2 = paddle2 + 8; } else if (paddle2Center > ballY + 30) { paddle2 = paddle2 - 8; }}
function moveEverything() { if (showingWinScreen) { return; }

computerMovement();
ballX = ballX + ballSpeedX; ballY = ballY + ballSpeedY; if (ballX > canvas.width) { if (ballY > paddle2 && ballY < paddle2 + paddleHeight) { ballSpeedX = -ballSpeedX;
var deltaY = ballY - (paddle2 + paddleHeight / 2); ballSpeedY = deltaY * 0.25;
} else { player1Score += 1; ballReset(); } } if (ballX < 0) { if (ballY > paddle1 && ballY < paddle1 + paddleHeight) { ballSpeedX = -ballSpeedX;
var deltaY = ballY - (paddle1 + paddleHeight / 2); ballSpeedY = deltaY * 0.25;
} else { player2Score += 1; ballReset(); } } if (ballY > canvas.height) { ballSpeedY = -ballSpeedY } if (ballY < 0) { ballSpeedY = -ballSpeedY }}

function drawNet() { for (var i = 0; i < canvas.height; i += 40) { colorRect(canvas.width / 2 - 1, i, 2, 20, 'white'); }}
function drawEverything() {
colorRect(0, 0, canvas.width, canvas.height, 'black');
if (showingWinScreen) { canvasContext.fillStyle = 'white';
if (player1Score >= WinningScore) { canvasContext.font = 'italic 60pt Calibri'; canvasContext.fillText('Left Player Won!', 475, 350); } else if (player2Score >= WinningScore) { canvasContext.font = 'italic 60pt Calibri'; canvasContext.fillText('Right Player Won', 475, 350); }
canvasContext.font = 'italic 80pt Calibri'; canvasContext.fillText('click to continue', 400, 600);

return; }
drawNet();
colorRect(0, paddle1, paddleThickness, paddleHeight, 'white'); colorRect(canvas.width - paddleThickness, paddle2, paddleThickness, paddleHeight, 'white'); colorCircle(ballX, ballY, 10, 'white')
canvasContext.fillText(player1Score, 100, 100); canvasContext.fillText(player2Score, canvas.width - 100, 100);

}
function colorRect(leftX, topY, width, height, drawColor) { canvasContext.fillStyle = drawColor; canvasContext.fillRect(leftX, topY, width, height);}
function colorCircle(centerX, centerY, radius, drawColor) { canvasContext.fillStyle = drawColor; canvasContext.beginPath(); canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true); canvasContext.fill();}
<html>
<head>
<title>Ping Pong Game</title>
</head>
<body bgcolor="#FFB630">
<canvas id="Mycanvas" width="1600" height="800"></canvas>

<div> <h1>The Ping Pong Game</h1>
<h2>Use the mouse to control the paddle!</h2> </div>
</body>
</html>

jQuery: How to detect arrow key press only on certain element

Instead of

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

in your javascript code have

$(<selector>).keydown(function(e) {

where <selector> points to the element you want to track.

UPDATE

Better - since you mention dynamically added elements, use delegation structure of event binding:

$(document).on("keydown", ".<yourClassName>", function(e) {

Binding arrow keys in JS/jQuery

document.onkeydown = function(e) {
switch(e.which) {
case 37: // left
break;

case 38: // up
break;

case 39: // right
break;

case 40: // down
break;

default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
};

If you need to support IE8, start the function body as e = e || window.event; switch(e.which || e.keyCode) {.


(edit 2020)

Note that KeyboardEvent.which is now deprecated. See this example using KeyboardEvent.key for a more modern solution to detect arrow keys.



Related Topics



Leave a reply



Submit