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.
Related
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.
In the following code:
$(document).keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 40) {
alert("down pressed");
} else if (code == 38) {
alert("up pressed");
}
});
I'm trying to detect if the down key or up key is pressed. Why isn't it working?
Fiddle
http://jsfiddle.net/K9uDn/10/
I'm in chrome
Use keydown instead of keypress, some browsers does not fire keypress when an "special key (like arrows)" are pressed
jQuery's keypress method isn't very stable. Use on('keydown') instead.
See: http://jsfiddle.net/K9uDn/9/
Here's the Fiddle of a fixed version of the javascript code
with extra buttons trapped using a switch/case statement
$(document).on('keydown',function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch (code){
case 34:
alert("Page down pressed");
break;
case 33:
alert("Page up pressed");
break;
case 40:
alert("Down pressed");
break;
case 38:
alert("Up pressed");
break;
case 37:
alert("Left pressed");
break;
case 39:
alert("Right pressed");
break;
}
on('keyup') does not work in IE. Not in version 9 at least.
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
I don't know much about how it works. My guess is JavaScript, but anyway.
When you go to your dashboard in Tumblr you can go back and forth between pages in your feed with your keyboard. ← to go forward to newer posts and → to go to older posts.
Can someone help me figure out how they do this.
Well, what you have do is set up a "keyup" event listener for your document element that reads which key your user pressed, then execute an action if the keycode matches the code for your left or right keys.
The "left" key's keycode is 37. the right is 39. So the listener for the "left" key you would set up is this:
document.onkeyup = function(e){
if (e.keyCode == 37) { //"left" key.
//your code
}
if (e.keyCode == 39) { //"right" key.
//your code
}
}
Figured it out:
<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 37:
window.location = "{PreviousPage}";
break;
case 39:
window.location = "{NextPage}";
break;
}
}
</script>