Related
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
};
}
I'm creating a canvas game for fun, and I'm trying to re-factor some of my multiple else if statements to use object lookup tables instead.
This is my current code for assigning variable values on keydown:
function keyDown(e) {
keypressed = true;
if (e.keyCode == 39 || e.keyCode == 68) {rightKey = true; }
else if (e.keyCode == 37 || e.keyCode == 65) {leftKey = true;}
else if (e.keyCode == 38 || e.keyCode == 87) {upKey = true; }
else if (e.keyCode == 40 || e.keyCode == 83) {downKey = true; }
else if (e.keyCode == 80) { isPaused = !isPaused; document.body.classList.toggle('pause'); }
if (e.keyCode === 69) { startHit(); }
}
I want to assign both wsad keys and the arrow keys to do the same thing, thus the use of || in the if conditions.
I read that using an object literal lookup table is a faster way to achieve this and this is my attempt:
var codes = {
39 : function() {
return rightKey = true;
},
37 : function() {
return leftKey = true;
},
38 : function() {
return upKey = true;
},
40 : function() {
return downKey = true;
},
80 : function() {
isPaued = !isPaused;
document.body.classList.toggle('pause');
},
69 : startHit
}
codes[68] = codes[39];
codes[65] = codes[37];
codes[87] = codes[38];
codes[83] = codes[40];
function keyDown(e) {
keypressed = true;
codes[e.keyCode]();
}
This works just fine, but I'm not sure the assignment of the bottom keys is the best way to do this? I can't obviously use the || operator in the left hand assignment, so would there be a cleaner way to do this or should I just stick with the else ifs?
Also, I know I could use a switch statement, but I feel like it would look similar to the way I've done above.
Any advice would be great. Thanks.
Why not use a switch statement?
function keyDown(e) {
keypressed = true;
switch (e.keyCode) {
case 39:
case 68:
rightKey = true;
break;
case 37:
case 65:
leftKey = true;
break;
case 38:
case 87:
upKey = true;
break;
case 40:
case 83:
downKey = true;
break;
case 80:
isPaused = !isPaused;
document.body.classList.toggle('pause');
break;
case 69:
startHit();
}
}
what about this?
var codes = function (){
function rightKey(){
rightKey = true;
}
function leftKey() {
leftKey = true;
}
return {
39 : rightKey,
37 : leftKey,
'...': '...',
68 : rightKey,
65 : leftKey
}}()
i want to ask how can i change the web page when the arrow key pushed by user , like a web of manga/book if we want to next page we just push the arrow key
sorry for my english , thanks before
You can use jQuery for that:
$(document).keydown(function(e) {
if (e.which == 37) {
alert("left");
e.preventDefault();
return false;
}
if (e.which == 39) {
alert("right");
e.preventDefault();
return false;
}
});
If you wish to use the jQuery framework, then look at Binding arrow keys in JS/jQuery
In plain javascript, I'll go with :
document.onkeydown = function (e) {
e = e || window.event;
var charCode = (e.charCode) ? e.charCode : e.keyCode;
if (charCode == 37) {
alert('left');
}
else if (charCode == 39) {
alert('right');
}
};
Here is a non jQuery option:
document.onkeydown = arrowChecker;
function arrowChecker(e) {
e = e || window.event;
if (e.keyCode == '37') { //left
document.location.href = "http://stackoverflow.com/";
}
else if (e.keyCode == '39') { //right
document.location.href = "http://google.com/";
}
}
Canvas auto runs when you click on another window and come back.
I have added key listeners and they make the ship move when you click w a s d or up, left, right, down.
It all works fine until you click two buttons like up and right and then click on another tab or window and come back. Then it will just keep moving not listening to your input.
What I think the problem is, is that when you click off the page the canvas never gets to check if the key was left up.But how do I make all the keys act like they were unpressed when you click off the screen?
Also the enemy disappera when you move off screen
This is what happens when buttons are pressed:
Player.prototype.checkKeys = function() //these functions are in the PLayer class
{
if(this.isUpKey == true)//if true
{
if(Player1.drawY >= 0)
{
this.drawY -= this.Speed;
}
}
if(this.isRightKey == true)
{
if(Player1.drawX <= (canvasWidthShips - this.playerWidth))
{
this.drawX += this.Speed;
}
}
if(this.isDownKey == true)
{
if(Player1.drawY <= (canvasHeightShips - this.playerHeight))
{
this.drawY += this.Speed;
}
}
if(this.isLeftKey == true)
{
if(Player1.drawX >= 0)
{
this.drawX -= this.Speed;
}
}
};
And these are my simple functions to check when a key is pressed down, I dont think the error is here but not sure?
function checkKeyDown(e)
{
if (Paused == false)
{
var KeyID = e.KeyCode || e.which;
if (KeyID === 38 || KeyID === 87) //up and w keyboard buttons
{
Player1.isUpKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 39 || KeyID === 68) //right and d keyboard buttons
{
Player1.isRightKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 40 || KeyID === 83) //down and s keyboard buttons
{
Player1.isDownKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 37 || KeyID === 65) //left and a keyboard buttons
{
Player1.isLeftKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
}
else if (Paused == true)
{
Player1.isUpKey = false;
Player1.isDownKey = false;
Player1.isRightKey = false;
Player1.isLeftKey = false;
}
}
function checkKeyUp(e)
{
if (Paused == false)
{
var KeyID = e.KeyCode || e.which;
if (KeyID === 38 || KeyID === 87) //up and w keyboard buttons
{
Player1.isUpKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 39 || KeyID === 68) //right and d keyboard buttons
{
Player1.isRightKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 40 || KeyID === 83) //down and s keyboard buttons
{
Player1.isDownKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 37 || KeyID === 65) //left and a keyboard buttons
{
Player1.isLeftKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
}
else if (Paused == true)
{
Player1.isUpKey = false;
Player1.isDownKey = false;
Player1.isRightKey = false;
Player1.isLeftKey = false;
}
}
Would it be ok to just pause the game? You can listen for onblur on the browser window which gets triggered when it loses focus and then just pause the game in the event handler.
window.onblur = function() {
// Add logic to pause the game here...
Paused = true;
};
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
};
}