javascript keypress to control animation - javascript

Space Invader game: I want to control the 'base gun' (move it left and right and fire missiles at the invaders. So I need a keypress or (keydown?) event to change a variable (x coordinate) and a key press event to fire a missile.
Can anyone show me how the keypress event is detected and the variable is changed?

document.onkeydown = function(e) {
var key = e.keyCode;
if (key===37) {//left arrow pressed
} else if (key===39) {//right arrow pressed
}
}

Like this?
document.onkeydown = checkKey;
var xCoord = 100;
function checkKey(e) {
e = e || window.event;
switch (e.keyCode) {
case 37 : // left
xCoord -= 5;
break;
case 39 : // right
xCoord += 5;
break;
}
}
Exciting fiddle: http://jsfiddle.net/u5eJp/

Couple things I would like to add to the other answers:
1) Use constants to make it easier on yourself
2) There is no way to check if a key is currently pressed in javascript, so you should keep track of what is currently pressed as well
var pressed = {
up: false,
down: false,
left: false,
right: false
};
var LEFT_ARROW = 37;
var UP_ARROW = 38;
var RIGHT_ARROW = 39;
var DOWN_ARROW = 40;
document.onkeydown = function (e) {
e = e || window.event;
switch (e.keyCode) {
case LEFT_ARROW:
pressed.left = true;
break;
case UP_ARROW:
pressed.up = true;
break;
case RIGHT_ARROW:
pressed.right = true;
break;
case DOWN_ARROW:
pressed.down = true;
break;
default:
break;
}
}
//update position separately
function updatePos() {
if (pressed.up) { //change y up }
if (pressed.down) { //change y down }
if (pressed.left) { //change x left }
if (pressed.right) { //change x right }
}
Hope this helps, and good luck!

Related

cancel an if statement if another statement comes true

I have this function that plays different sounds to different keys. But if I press a key, then press another key right away, the previous sound will still play.
My question is, how do I cancel the previous sound when a new one is played?
Here's the code:
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(evt) {
if (evt.keyCode == "81") { //q
document.getElementById('enklyd').play();
}
if (evt.keyCode == "87") { //w
document.getElementById('lyd1').play();
}
if (evt.keyCode == "69") { //e
document.getElementById('lyd2').play();
}
if (evt.keyCode == "82") { //r
document.getElementById('lyd3').play();
}
if (evt.keyCode == "84") { //t
document.getElementById('lyd4').play();
}
if (evt.keyCode == "89") { //y
document.getElementById('lyd5').play();
}
}
This isn't really a matter of "stopping" the if statement because they are individually doing their job correctly. What you want to stop is the sound clip being played.
For this you can use the .pause() method, set the .currentTime to 0, or I believe you can also set the volume to 0 and just let it play out.
As mentioned in a comment, there are a few SO questions that may have already answered this. Is there a unique situation that isn't being answered in those?
I think this works for you:
var e = document.getElementById('enklyd');
function checkKeyPressed(evt) {
if (evt.keyCode == "81") { //q
e.pause();
e.currentTime = 0;
e = document.getElementById('enklyd');
e.play();
}
if (evt.keyCode == "87") { //w
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd1');
e.play();
}
if (evt.keyCode == "69") { //e
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd2');
e.play();
}
if (evt.keyCode == "82") { //r
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd3');
e.play();
}
if (evt.keyCode == "84") { //t
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd4');
e.play();
}
if (evt.keyCode == "89") { //y
e.pause();
e.currentTime = 0;
e = document.getElementById('lyd5');
e.play();
}
}
Actually, the issue is not regarding the if condition. But you can try the following code, I think this will work fine for you.
window.addEventListener("keydown", checkKeyPressed, false);
var keyMap = {
"81": "enklyd", //q
"87": "lyd1", //w
"69": "lyd2", //e
"82": "lyd3", //r
"84": "lyd4", //t
"89": "lyd5", //y
};
var prevPlayed = null, target = null, prevTarget = null;
function checkKeyPressed(evt) {
prevTarget = document.getElementById(keyMap[prevPlayed])
target = document.getElementById(keyMap[evt.keyCode]);
if (prevPlayed !== null && prevTarget !== null)
prevTarget.pause();
if (keyMap[evt.keyCode] && target !== null) {
target.currentTime = 0;
target.play();
}
prevPlayed = evt.keyCode;
}
You should use 'switch' instead of using 'if'.Just add a common class to all your elements
const yourDiv = document.querySelector('yourDiv');
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(evt) {
yourDiv.currentTime = 0;
switch(evt) {
case '81':
document.getElementById('enklyd').play();
break;
case '87' :
document.getElementById('lyd1').play();
break;
case '69' :
document.getElementById('lyd2').play();
break;
case '82' :
document.getElementById('lyd3').play();
break;
case '84' :
document.getElementById('lyd4').play();
break;
case '89' :
document.getElementById('lyd5').play();
break;
default :
return null;
}
}

jQuery event: keypress not working with Firefox or IE, and keyup not working with IE [duplicate]

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).
Arrow keys are only triggered by onkeydown, not onkeypress.
The keycodes are:
left = 37
up = 38
right = 39
down = 40
On key up and down call function. There are different codes for each key.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
}
else if (e.keyCode == '40') {
// down arrow
}
else if (e.keyCode == '37') {
// left arrow
}
else if (e.keyCode == '39') {
// right arrow
}
}
event.key === "ArrowRight"...
More recent and much cleaner: use event.key. No more arbitrary number codes! If you are transpiling or know your users are all on modern browsers, use this!
node.addEventListener('keydown', function(event) {
const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
});
Verbose Handling:
switch (event.key) {
case "ArrowLeft":
// Left pressed
break;
case "ArrowRight":
// Right pressed
break;
case "ArrowUp":
// Up pressed
break;
case "ArrowDown":
// Down pressed
break;
}
Modern Switch Handling:
const callback = {
"ArrowLeft" : leftHandler,
"ArrowRight" : rightHandler,
"ArrowUp" : upHandler,
"ArrowDown" : downHandler,
}[event.key]
callback?.()
NOTE: The old properties (.keyCode and .which) are Deprecated.
"w", "a", "s", "d" for direction, use event.code
To support users who are using non-qwerty/English keyboard layouts, you should instead use event.code. This will preserve physical key location, even if resulting character changes.
event.key would be , on Dvorak and z on Azerty, making your game unplayable.
const {code} = event
if (code === "KeyW") // KeyA, KeyS, KeyD
Optimally, you also allow key remapping, which benefits the player regardless of their situation.
P.S. event.code is the same for arrows
key Mozilla Docs
code Mozilla Docs
Supported Browsers
Possibly the tersest formulation:
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 38:
alert('up');
break;
case 39:
alert('right');
break;
case 40:
alert('down');
break;
}
};
Demo (thanks to user Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/
This should work cross-browser. Leave a comment if there is a browser where it does not work.
There are other ways to get the key code (e.which, e.charCode, and window.event instead of e), but they should not be necessary. You can try most of them out at http://www.asquare.net/javascript/tests/KeyCode.html.
Note that event.keycode does not work with onkeypress in Firefox, but it does work with onkeydown.
Use keydown, not keypress for non-printable keys such as arrow keys:
function checkKey(e) {
e = e || window.event;
alert(e.keyCode);
}
document.onkeydown = checkKey;
The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html
Modern answer since keyCode is now deprecated in favor of key:
document.onkeydown = function (e) {
switch (e.key) {
case 'ArrowUp':
// up arrow
break;
case 'ArrowDown':
// down arrow
break;
case 'ArrowLeft':
// left arrow
break;
case 'ArrowRight':
// right arrow
}
};
I believe the most recent method would be:
document.addEventListener("keydown", function(event) {
event.preventDefault();
const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
switch (key) { // change to event.key to key to use the above variable
case "ArrowLeft":
// Left pressed
<do something>
break;
case "ArrowRight":
// Right pressed
<do something>
break;
case "ArrowUp":
// Up pressed
<do something>
break;
case "ArrowDown":
// Down pressed
<do something>
break;
}
});
This assumes the developer wants the code to be active anywhere on the page and the client should ignore any other key presses. Eliminate the event.preventDefault(); line if keypresses, including those caught by this handler should still be active.
function checkArrowKeys(e){
var arrs= ['left', 'up', 'right', 'down'],
key= window.event? event.keyCode: e.keyCode;
if(key && key>36 && key<41) alert(arrs[key-37]);
}
document.onkeydown= checkArrowKeys;
Here's an example implementation:
var targetElement = $0 || document.body;
function getArrowKeyDirection (keyCode) {
return {
37: 'left',
39: 'right',
38: 'up',
40: 'down'
}[keyCode];
}
function isArrowKey (keyCode) {
return !!getArrowKeyDirection(keyCode);
}
targetElement.addEventListener('keydown', function (event) {
var direction,
keyCode = event.keyCode;
if (isArrowKey(keyCode)) {
direction = getArrowKeyDirection(keyCode);
console.log(direction);
}
});
Here's how I did it:
var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40;
var keystate;
document.addEventListener("keydown", function (e) {
keystate[e.keyCode] = true;
});
document.addEventListener("keyup", function (e) {
delete keystate[e.keyCode];
});
if (keystate[leftKey]) {
//code to be executed when left arrow key is pushed.
}
if (keystate[upKey]) {
//code to be executed when up arrow key is pushed.
}
if (keystate[rightKey]) {
//code to be executed when right arrow key is pushed.
}
if (keystate[downKey]) {
//code to be executed when down arrow key is pushed.
}
I've been able to trap them with jQuery:
$(document).keypress(function (eventObject) {
alert(eventObject.keyCode);
});
An example: http://jsfiddle.net/AjKjU/
That is the working code for chrome and firefox
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
function leftArrowPressed() {
alert("leftArrowPressed" );
window.location = prevUrl
}
function rightArrowPressed() {
alert("rightArrowPressed" );
window.location = nextUrl
}
function topArrowPressed() {
alert("topArrowPressed" );
window.location = prevUrl
}
function downArrowPressed() {
alert("downArrowPressed" );
window.location = nextUrl
}
document.onkeydown = function(evt) {
var nextPage = $("#next_page_link")
var prevPage = $("#previous_page_link")
nextUrl = nextPage.attr("href")
prevUrl = prevPage.attr("href")
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
leftArrowPressed(nextUrl);
break;
case 38:
topArrowPressed(nextUrl);
break;
case 39:
rightArrowPressed(prevUrl);
break;
case 40:
downArrowPressed(prevUrl);
break;
}
};
</script>
</head>
<body>
<p>
<a id="previous_page_link" href="http://www.latest-tutorial.com">Latest Tutorials</a>
<a id="next_page_link" href="http://www.zeeshanakhter.com">Zeeshan Akhter</a>
</p>
</body>
</html>
Arrow Keys are triggered on keyup
$(document).on("keyup", "body", function(e) {
if (e.keyCode == 38) {
// up arrow
console.log("up arrow")
}
if (e.keyCode == 40) {
// down arrow
console.log("down arrow")
}
if (e.keyCode == 37) {
// left arrow
console.log("lefy arrow")
}
if (e.keyCode == 39) {
// right arrow
console.log("right arrow")
}
})
onkeydown allows ctrl, alt, shits
onkeyup allows tab, up arrows, down arrows, left arrows, down arrows
I was also looking for this answer until I came across this post.
I've found another solution to know the keycode of the different keys, courtesy to my problem. I just wanted to share my solution.
Just use keyup/keydown event to write the value in the console/alert the same using event.keyCode. like-
console.log(event.keyCode)
// or
alert(event.keyCode)
- rupam
That's shorter.
function IsArrows (e) {
return (e.keyCode >= 37 && e.keyCode <= 40);
}
This library rocks!
https://craig.is/killing/mice
Mousetrap.bind('up up down down left right left right b a enter', function() {
highlight([21, 22, 23]);
});
You need to press the sequence a bit fast to highlight the code in that page though.
With key and ES6.
This gives you a separate function for each arrow key without using switch and also works with the 2,4,6,8 keys in the numpad when NumLock is on.
const element = document.querySelector("textarea"),
ArrowRight = k => {
console.log(k);
},
ArrowLeft = k => {
console.log(k);
},
ArrowUp = k => {
console.log(k);
},
ArrowDown = k => {
console.log(k);
},
handler = {
ArrowRight,
ArrowLeft,
ArrowUp,
ArrowDown
};
element.addEventListener("keydown", e => {
const k = e.key;
if (handler.hasOwnProperty(k)) {
handler[k](k);
}
});
<p>Click the textarea then try the arrows</p>
<textarea></textarea>
Re answers that you need keydown not keypress.
Assuming you want to move something continuously while the key is pressed, I find that keydown works for all browsers except Opera. For Opera, keydown only triggers on 1st press. To accommodate Opera use:
document.onkeydown = checkKey;
document.onkeypress = checkKey;
function checkKey(e)
{ etc etc
If you use jquery then you can also do like this,
$(document).on("keydown", '.class_name', function (event) {
if (event.keyCode == 37) {
console.log('left arrow pressed');
}
if (event.keyCode == 38) {
console.log('up arrow pressed');
}
if (event.keyCode == 39) {
console.log('right arrow pressed');
}
if (event.keyCode == 40) {
console.log('down arrow pressed');
}
});
control the Key codes %=37 and &=38... and only arrow keys left=37 up=38
function IsArrows (e) {
return ( !evt.shiftKey && (e.keyCode >= 37 && e.keyCode <= 40));
}
If you want to detect arrow keypresses but not need specific in Javascript
function checkKey(e) {
if (e.keyCode !== 38 || e.keyCode !== 40 || e.keyCode !== 37 || e.keyCode !== 39){
// do something
};
}

How to simulate multiple keypress event at the same time

I found this way, but with it I can only set one keycode in .which, I want to simulate the keys ALT+space+x at the same time.
For ALT I can use .altKey = true;
$(".btn").click(function() {
var e = jQuery.Event("keypress");
e.which = 88; // x code value
e.altKey = true; // Alt key pressed
$("input").trigger(e);
});
How do I add space keycode?
I apologize for my previous answer. I thought about how to handle. Now I modify code to handle and trigger:
You can implement it with two events: keyDown and keyUp like this:
var x,
alt,
space;
document.addEventListener('keydown', function (e) {
e = window.event ? event : e;
switch (e.keyCode) {
case 88:
x = true;
break;
case 18:
alt = true;
break;
case 32:
space = true;
break;
}
});
document.addEventListener('keyup', function (e) {
if (x && alt && space) {
alert("alt + space + x Pressed!");
}
x = alt = space = false;
});
function triggerEvent(eventName, keyCode) {
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.keyCode = keyCode || null;
if (document.createEvent) {
document.dispatchEvent(event);
} else {
document.fireEvent('on' + event.eventType, event);
}
}
triggerEvent('keydown', 88);
triggerEvent('keydown', 18);
triggerEvent('keydown', 32);
triggerEvent('keyup');
https://jsfiddle.net/m83omwq5/1/

Boundary for canvas game in Javascript

I have to make a game for school with html5 canvas Javascript.
I am new to javascript and still learning but i really need some help with this issue that i have and would appreciate it if someone could help me out. I tried several things but nothing seems to work and im at a loss.
So this is the code for the player object. It can move from left to right.
Now the problem is that it leaves the canvas. I want it to stay in the canvas on the x axes.
// Things to do when keys are down
function onKeyDown(event) {
// prevent arrow keys from scrolling the page
if (event.keyCode >= 37 && event.keyCode <= 39) event.preventDefault();
switch (event.keyCode) {
case 37:
player.vx = -1;
player.image = player.imgLeft;
break; // left key
// case 38: player.vy = -1; break; // up key
case 39:
player.vx = 1;
player.image = player.imgRight;
break; // right key
}
}
// Things to do when keys are up
function onKeyUp(event) {
switch (event.keyCode) {
case 37:
case 39:
player.vx = 0;
player.image = player.original;
break; // left or right key released
// case 38: player.vy = 0; break; // up or down key released
}
}
This is what i got so far....
if ((player.x >= 800) && (player.x <= 0)) {
} else {
}
You could consider adding two functions to check that you're within bounds.
(Essentially the same as your code, albeit with my true condition returned in what would be your else statement.)
// returns true if param is in range [0..799]
function isInXrange(intPos)
{
if ((intPos>=0) && (intPos<800))
return true;
else
return false;
}
// returns true if param is in range [0..599]
function isInYrange(intPos)
{
if ((intPos>=0) && (intPos<600))
return true;
else
return false;
}
You could then add a function to move the player and another to handle colliding with the walls/wandering out of bounds
function movePlayer()
{
if (isInXRange(player.x))
player.x += player.vx;
if (isInXRange(player.y))
player.y += player.vy;
}
function handleOutOfBounds()
{
if (isInXRange(player.x) == false)
{
// do something;
}
if (isInYRange(player.y) == false)
{
// do something else
}
}
Basically just test to see if x + width (optional: + velocity) > canvas.width and the same for height.

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).
Arrow keys are only triggered by onkeydown, not onkeypress.
The keycodes are:
left = 37
up = 38
right = 39
down = 40
On key up and down call function. There are different codes for each key.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
}
else if (e.keyCode == '40') {
// down arrow
}
else if (e.keyCode == '37') {
// left arrow
}
else if (e.keyCode == '39') {
// right arrow
}
}
event.key === "ArrowRight"...
More recent and much cleaner: use event.key. No more arbitrary number codes! If you are transpiling or know your users are all on modern browsers, use this!
node.addEventListener('keydown', function(event) {
const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
});
Verbose Handling:
switch (event.key) {
case "ArrowLeft":
// Left pressed
break;
case "ArrowRight":
// Right pressed
break;
case "ArrowUp":
// Up pressed
break;
case "ArrowDown":
// Down pressed
break;
}
Modern Switch Handling:
const callback = {
"ArrowLeft" : leftHandler,
"ArrowRight" : rightHandler,
"ArrowUp" : upHandler,
"ArrowDown" : downHandler,
}[event.key]
callback?.()
NOTE: The old properties (.keyCode and .which) are Deprecated.
"w", "a", "s", "d" for direction, use event.code
To support users who are using non-qwerty/English keyboard layouts, you should instead use event.code. This will preserve physical key location, even if resulting character changes.
event.key would be , on Dvorak and z on Azerty, making your game unplayable.
const {code} = event
if (code === "KeyW") // KeyA, KeyS, KeyD
Optimally, you also allow key remapping, which benefits the player regardless of their situation.
P.S. event.code is the same for arrows
key Mozilla Docs
code Mozilla Docs
Supported Browsers
Possibly the tersest formulation:
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 38:
alert('up');
break;
case 39:
alert('right');
break;
case 40:
alert('down');
break;
}
};
Demo (thanks to user Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/
This should work cross-browser. Leave a comment if there is a browser where it does not work.
There are other ways to get the key code (e.which, e.charCode, and window.event instead of e), but they should not be necessary. You can try most of them out at http://www.asquare.net/javascript/tests/KeyCode.html.
Note that event.keycode does not work with onkeypress in Firefox, but it does work with onkeydown.
Use keydown, not keypress for non-printable keys such as arrow keys:
function checkKey(e) {
e = e || window.event;
alert(e.keyCode);
}
document.onkeydown = checkKey;
The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html
Modern answer since keyCode is now deprecated in favor of key:
document.onkeydown = function (e) {
switch (e.key) {
case 'ArrowUp':
// up arrow
break;
case 'ArrowDown':
// down arrow
break;
case 'ArrowLeft':
// left arrow
break;
case 'ArrowRight':
// right arrow
}
};
I believe the most recent method would be:
document.addEventListener("keydown", function(event) {
event.preventDefault();
const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
switch (key) { // change to event.key to key to use the above variable
case "ArrowLeft":
// Left pressed
<do something>
break;
case "ArrowRight":
// Right pressed
<do something>
break;
case "ArrowUp":
// Up pressed
<do something>
break;
case "ArrowDown":
// Down pressed
<do something>
break;
}
});
This assumes the developer wants the code to be active anywhere on the page and the client should ignore any other key presses. Eliminate the event.preventDefault(); line if keypresses, including those caught by this handler should still be active.
function checkArrowKeys(e){
var arrs= ['left', 'up', 'right', 'down'],
key= window.event? event.keyCode: e.keyCode;
if(key && key>36 && key<41) alert(arrs[key-37]);
}
document.onkeydown= checkArrowKeys;
Here's an example implementation:
var targetElement = $0 || document.body;
function getArrowKeyDirection (keyCode) {
return {
37: 'left',
39: 'right',
38: 'up',
40: 'down'
}[keyCode];
}
function isArrowKey (keyCode) {
return !!getArrowKeyDirection(keyCode);
}
targetElement.addEventListener('keydown', function (event) {
var direction,
keyCode = event.keyCode;
if (isArrowKey(keyCode)) {
direction = getArrowKeyDirection(keyCode);
console.log(direction);
}
});
Here's how I did it:
var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40;
var keystate;
document.addEventListener("keydown", function (e) {
keystate[e.keyCode] = true;
});
document.addEventListener("keyup", function (e) {
delete keystate[e.keyCode];
});
if (keystate[leftKey]) {
//code to be executed when left arrow key is pushed.
}
if (keystate[upKey]) {
//code to be executed when up arrow key is pushed.
}
if (keystate[rightKey]) {
//code to be executed when right arrow key is pushed.
}
if (keystate[downKey]) {
//code to be executed when down arrow key is pushed.
}
I've been able to trap them with jQuery:
$(document).keypress(function (eventObject) {
alert(eventObject.keyCode);
});
An example: http://jsfiddle.net/AjKjU/
That is the working code for chrome and firefox
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
function leftArrowPressed() {
alert("leftArrowPressed" );
window.location = prevUrl
}
function rightArrowPressed() {
alert("rightArrowPressed" );
window.location = nextUrl
}
function topArrowPressed() {
alert("topArrowPressed" );
window.location = prevUrl
}
function downArrowPressed() {
alert("downArrowPressed" );
window.location = nextUrl
}
document.onkeydown = function(evt) {
var nextPage = $("#next_page_link")
var prevPage = $("#previous_page_link")
nextUrl = nextPage.attr("href")
prevUrl = prevPage.attr("href")
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
leftArrowPressed(nextUrl);
break;
case 38:
topArrowPressed(nextUrl);
break;
case 39:
rightArrowPressed(prevUrl);
break;
case 40:
downArrowPressed(prevUrl);
break;
}
};
</script>
</head>
<body>
<p>
<a id="previous_page_link" href="http://www.latest-tutorial.com">Latest Tutorials</a>
<a id="next_page_link" href="http://www.zeeshanakhter.com">Zeeshan Akhter</a>
</p>
</body>
</html>
Arrow Keys are triggered on keyup
$(document).on("keyup", "body", function(e) {
if (e.keyCode == 38) {
// up arrow
console.log("up arrow")
}
if (e.keyCode == 40) {
// down arrow
console.log("down arrow")
}
if (e.keyCode == 37) {
// left arrow
console.log("lefy arrow")
}
if (e.keyCode == 39) {
// right arrow
console.log("right arrow")
}
})
onkeydown allows ctrl, alt, shits
onkeyup allows tab, up arrows, down arrows, left arrows, down arrows
I was also looking for this answer until I came across this post.
I've found another solution to know the keycode of the different keys, courtesy to my problem. I just wanted to share my solution.
Just use keyup/keydown event to write the value in the console/alert the same using event.keyCode. like-
console.log(event.keyCode)
// or
alert(event.keyCode)
- rupam
That's shorter.
function IsArrows (e) {
return (e.keyCode >= 37 && e.keyCode <= 40);
}
This library rocks!
https://craig.is/killing/mice
Mousetrap.bind('up up down down left right left right b a enter', function() {
highlight([21, 22, 23]);
});
You need to press the sequence a bit fast to highlight the code in that page though.
With key and ES6.
This gives you a separate function for each arrow key without using switch and also works with the 2,4,6,8 keys in the numpad when NumLock is on.
const element = document.querySelector("textarea"),
ArrowRight = k => {
console.log(k);
},
ArrowLeft = k => {
console.log(k);
},
ArrowUp = k => {
console.log(k);
},
ArrowDown = k => {
console.log(k);
},
handler = {
ArrowRight,
ArrowLeft,
ArrowUp,
ArrowDown
};
element.addEventListener("keydown", e => {
const k = e.key;
if (handler.hasOwnProperty(k)) {
handler[k](k);
}
});
<p>Click the textarea then try the arrows</p>
<textarea></textarea>
Re answers that you need keydown not keypress.
Assuming you want to move something continuously while the key is pressed, I find that keydown works for all browsers except Opera. For Opera, keydown only triggers on 1st press. To accommodate Opera use:
document.onkeydown = checkKey;
document.onkeypress = checkKey;
function checkKey(e)
{ etc etc
If you use jquery then you can also do like this,
$(document).on("keydown", '.class_name', function (event) {
if (event.keyCode == 37) {
console.log('left arrow pressed');
}
if (event.keyCode == 38) {
console.log('up arrow pressed');
}
if (event.keyCode == 39) {
console.log('right arrow pressed');
}
if (event.keyCode == 40) {
console.log('down arrow pressed');
}
});
control the Key codes %=37 and &=38... and only arrow keys left=37 up=38
function IsArrows (e) {
return ( !evt.shiftKey && (e.keyCode >= 37 && e.keyCode <= 40));
}
If you want to detect arrow keypresses but not need specific in Javascript
function checkKey(e) {
if (e.keyCode !== 38 || e.keyCode !== 40 || e.keyCode !== 37 || e.keyCode !== 39){
// do something
};
}

Categories