This question already has answers here:
Binding arrow keys in JS/jQuery
(16 answers)
Closed 6 years ago.
I want to give my content slider the ability to respond to keypress (LEFT ARROW key and RIGHT ARROW key) feature. I have read about some conflicts between several browsers and operation systems.
The user can navigate the content while he is on the global website (body).
Pseudo Code:
ON Global Document
IF Key Press LEFT ARROW
THEN animate #showroom css 'left' -980px
IF Key Press RIGHT ARROW
THEN animate #showroom css 'left' +980px
I need a solution without any crossover (Browsers, OSs) conflicts.
$("body").keydown(function(e) {
if(e.keyCode == 37) { // left
$("#showroom").animate({
left: "-=980"
});
}
else if(e.keyCode == 39) { // right
$("#showroom").animate({
left: "+=980"
});
}
});
$("body").keydown(function(e){
// left arrow
if ((e.keyCode || e.which) == 37)
{
// do something
}
// right arrow
if ((e.keyCode || e.which) == 39)
{
// do something
}
});
This works fine for me :
$(document).keypress(function (e){
if(e.keyCode == 37) // left arrow
{
// your action here, for example
$('#buttonPrevious').click();
}
else if(e.keyCode == 39) // right arrow
{
// your action here, for example
$('#buttonNext').click();
}
});
I prefer using this template:
$(document).keypress(function(e){
switch((e.keyCode ? e.keyCode : e.which)){
//case 13: // Enter
//case 27: // Esc
//case 32: // Space
case 37: // Left Arrow
$("#showroom").animate({left: "+=980"});
break;
//case 38: // Up Arrow
case 39: // Right Arrow
$("#showroom").animate({left: "-=980"});
break;
//case 40: // Down Arrow
}
});
The use of named functions expression may help to keep a cleaner code :
function go_left(){console.log('left');}
function go_up(){console.log('up');}
function go_right(){console.log('right');}
function go_down(){console.log('down');}
$(document).on('keydown',function(e){
var act={37:go_left, 38:go_up, 39:go_right, 40:go_down};
if(act[e.which]) var a=new act[e.which];
});
Related
So im just starting out learning Javascript, and I'm following the game tutorial in https://www.w3schools.com/graphics/game_obstacles.asp
This is the point i've gotten stuck at. If you check out the code in the example, they've added a working obstacle, but the game won't work with the keyboard. (only with buttons added to the site)
I want to be able to steer the character with my keyboard, and have a working obstacle, that will stop the game when the two touch.
I would appreciate any help i could get from this. (the code i use is in the example in the link above)
you will need a little bit more than in the shown example.
Here is a reference with an example for key pressed events Link
Short excerpt:
"Clear" JavaScript:
<script type="text/javascript">
function myKeyPress(e){
var keynum;
if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
}
</script>
<form>
<input type="text" onkeypress="return myKeyPress(event)" />
</form>
You could also solve it in jquery
JQuery:
$(document).keypress(function(event){
alert(String.fromCharCode(event.which));
});
Add this in you code to move the block.
window.addEventListener('keydown', function(event) {
console.log(event);
if(event.keyCode === 38){
console.log(event);
myGamePiece.speedY -= 1;
} else if (event.keyCode === 37){
myGamePiece.speedX = -1;
} else if (event.keyCode === 39){
myGamePiece.speedX = 1;
} else if (event.keyCode === 40){
myGamePiece.speedY = 1;
}
});
Do following changes:
Add onkeypress event in body element i.e. <body onkeypress="myFunction(event)" onload="startGame()" >.
Define myFunction function as following:
function myFunction(event)
{
switch(event.which || event.keyCode)
{
case 117: //Up 'U'
moveup();
break;
case 106: //Down 'J'
movedown();
break;
case 104: //Left 'H'
moveleft();
break;
case 107: //Right 'K'
moveright();
break;
}
}
You can get complete working code here. You can copy the complete code and run it locally.
I recently made a rudimentary html/css galery that is practicaly a table with next/previous buttons.The thing is I want to make it responsive to keyboard.Like if anyone hits the "left" button on keyboard it should go on the previous photo and if it hits the "right" button go on the next page.
I would love if you could make it with as less javascript/jquery as possible.I searched google for something like that but I haven't found none !
If you need any code of my website please let me know.
Please help !
You could capture the keyboard interaction using .on() and the keydown event, and decide what to do after the returned value like :
$(document).on("keydown", function (e) {
e.preventDefault();
var code = e.which || e.keyCode;
console.log(code)
if (code == 40) {
// down arrow pressed : do something
console.log("down arrow pressed")
}
});
See JSFIDDLE
The keyboard map of the navigation arrows are
// 37 = left arrow
// 38 = up arrow
// 39 = right arrow
// 40 = down arrow
EDIT : to avoid excessive use of if else if else, you could use switch (which performs better) like :
$(document).on("keydown", function (e) {
e.preventDefault();
var code = e.which || e.keyCode;
switch (code) {
case 37:
console.log("left arrow pressed")
break;
case 38:
console.log("up arrow pressed")
break;
case 39:
console.log("right arrow pressed")
break;
case 40:
console.log("down arrow pressed")
break;
default:
return false
}
});
See updated JSFIDDLE
JFK's answer is correct, but I extended that a little
$(document).on("keydown", function (e) {
var code = e.which || e.keyCode;
if (code == 40 || code == 39) { // down & right
// replace selector with your button id/class
$('.btn-next').click();
} else if (code == 38 || code == 37) { // up & left
// replace selector with your button id/class
$('.btn-previous').click();
}
});
The code simulates a click on the next/previous buttons so you are able to place any code which should happen when clicking or key pressing only once.
How to run a code in javascript when Left Or Right Arrow Keys is Triggered on the keyboard?
I am kinda Newbie to programming.
Can someone please guide me?
function leftpress() {
//do action
}
function rightpress() {
//do action
}
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 39://left arrow
leftpress();
break;
case 37://right arrow
rightpress();
break;
}
};
this is the exact code, try it ..
-you can ask me again if you need help.
You need to attach event handler for tracking the key-board events
document.addEventListener("keydown", keyDownevent, false);
function keyDownevent(e) {
var keyCode = e.keyCode;
if (e.keyCode === 37) {//right
// Your Code
}
else if (e.keyCode === 38) {//UP
// Your Code
}
else if (e.keyCode === 39) {//left
// Your Code
}
else if (e.keyCode === 40) {//DOWN
// Your Code
}
}
Working Example
It's simple with Jquery:
Try this :
$(document).keydown(function (e) {
e.stopImmediatePropagation();
if (e.keyCode === 37) {//right
// Your Code
}
else if (e.keyCode === 38) {//UP
// Your Code
}
else if (e.keyCode === 39) {//left
// Your Code
}
else if (e.keyCode === 40) {//DOWN
// Your Code
}
});
If you are new to Javascript, then may I advise on using libraries to make things easier (because you may end up fixing a lot of cross-browser issues) :)
jQuery is a good one, here are some keyboard events. http://api.jquery.com/category/events/keyboard-events/
First you need to get the value of the key you pressed, with jquery it is done like this:
$(‘#keyval’).keyup(function(e) {
console.log(e.which)
});
Then you do the test to see what value those keys has and then check for keyup event, check if it has than value and then do the action, like this:
$(document).keypress(function(e) {
if(e.which == //arrow value) {
// your action
}
});
I have not tested it but it must work.
Please Help! I have spent a week to complete this game and this is the final huddle i have been stuck with for a couple of days now. I know some techy out there would probably take a glance and flick something in place. But I'm not very sophisticated with javascript and therefore need some help.
$(document).keydown(function(e){
// left arrow
if (e.keyCode == 37 && currentCell > 0) {
currentCell--;
ChangeCurrentCell();
return false;
}
// up arrow
if (e.keyCode == 38 && currentRow > 0) {
currentRow--;
ChangeCurrentCell();
return false;
}
// right arrow
if (e.keyCode == 39 && currentCell < MAX_CELL) {
currentCell++;
ChangeCurrentCell();
return false;
}
//down arrow
if (e.keyCode == 40 && currentRow < MAX_ROW) {
currentRow++;
ChangeCurrentCell();
return false;
}
// enter key
if (e.keyCode == 13) {
}
});
function ChangeCurrentCell()
{
document.getElementById(Boxes[currentRow + currentCell]).focus();
SimulateMouseOver(document.getElementById(Boxes[currentRow + currentCell]));
}
// function will trigger event of selecting current focus.
function selectElement()
{
}
$(document).ready(function(){
loadDivs()
// will give initial focus to top left element paving way for key navigation
ChangeCurrentCell();
// above gives first element in Boxes the focus when loading.
The div element will not focus despite getting it and calling the focus method, i have tried to trigger mousehover on the element with no luck. Please assist me, i put my masters thesis aside despite already being on a tight schedule to do this game which is a requirement for a job position. I have done whole the whole game logic and it all works well, if i send the code in as it is it will definitely be discarded because it doesnt meet the key navigation requirement ... i am desperate i will even pay if i need to -frustrated Student
Look at this
It's my solution for a test, maybe the same...maybe can help you :) If it is, please use it as a hint and don't copy all my code :D
Regards,
L.
You can bind to the document.keydown event to capture key strokes. Then you can use event.which (normalized by jQuery) to determine which key was pressed.
$(document).on("keydown", function (event) {
if (event.which === 37) {
//code for left arrow
} else if (event.which === 38) {
//code for up arrow
} else if (event.which === 39) {
//code for right arrow
} else if (event.which === 40) {
//code for down arrow
}
});
UPDATE
I just noticed you didn't tag your question with jQuery. To use native JS you'll have to change how you bind to the document.keydown event and how you determine the key that was pressed (different browser implementations store the info under different indexes of the event object).
to make it more convenient () not necessary:
`var LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, SPACE = 32;`
then bind to keydown, keypress doesn't catch arrow keys
and do something like this:
$(document).bind("keydown", function (e){
var which = e.which;
var navigationKeyWasPressed = which !== undefined && which >= 39 && which <= 40;
//do nothing if no significant key was pressed
if (!navigationKeyWasPressed ) {
return;
}
if ($(".selectedWithKey").length === 1){
switch (which) {
case LEFT:
//...
break;
case UP:
//...
break;
case RIGHT:
//...
break;
case DOWN:
//...
break;
case SPACE:
//turn card
break;
default: //non arrow pressed
//...
}
} else {
// if no card is selected, select one to start arrow navigation
$(".sponsor:first").addClass("selectedWithKey")
}
});
I have made a game using HTML5 Canvas Element, Javascript for facebook. You can visit it here, http://apps.facebook.com/snaqe_game. The problem I am facing is that when I press down arrow key, used for moving the snake implemented using Javascript onkeydown event, the game works normally but the scrollbars go up and down. I tried making an textbox(#activ) and setting focus to it. It worked but when I tried to make it invisible, it failed.
document.onkeydown = function(event) {
document.getElementById('activ').focus()
if (!allowPressKeys) {
return null;
}
var keyCode;
if(event == null) {
keyCode = window.event.keyCode;
} else {
keyCode = event.keyCode;
}
switch(keyCode) {
case 37:
if (direction != "right") {
moveLeft();
}
break;
case 38:
if (direction != "down") {
moveUp();
}
break;
case 39:
if (direction != "left") {
moveRight();
}
break;
case 40:
if (direction != "up") {
moveDown();
}
break;
default:
break;
}
}
At the end of your document.onkeydown function (after line 197 in snake.js), add
if (event.preventDefault) { event.preventDefault(); }
if (event.stopPropagation) { event.stopPropagation(); }
return false;
This prevents the browser from responding to the event, beyond executing your function.
You may also need to replace return null; on line 161 with these three lines.
event.stopPropagation in the MDN Docs
event.preventDefault in the MDN Docs
Early Event Handlers: Prevent Default at QuirksMode