JavaScript Keyboard Event Not Firing - javascript

For some very odd reason when you press keys in the order of forward, spacebar, and left. Left does not fire and returns spacebar instead. Any other combination of three keys works perfectly fine, but not that one. Any clues as to why?
var Ctrl = {
init: function() {
window.addEventListener('keydown', this.keyDown, true);
window.addEventListener('keyup', this.keyUp, true);
},
keyDown: function(event) {
console.log(event.keyCode);
switch(event.keyCode) {
case 37: // Left
Ctrl.left = true;
break;
case 39: // Right
Ctrl.right = true;
break;
case 38: // up
Ctrl.up = true;
break;
case 40: // down
Ctrl.down = true;
break;
case 32:
Ctrl.space = true;
break;
default:
break;
}
},
keyUp: function(event) {
switch(event.keyCode) {
case 37: // Left
Ctrl.left = false;
break;
case 39: // Right
Ctrl.right = false;
break;
case 38:
Ctrl.up = false;
break;
case 40:
Ctrl.down = false;
break;
case 32:
Ctrl.space = false;
break;
default:
break;
}
}
};

Maybe one of your keys is activating an unwanted default behavior. You can try to add event.preventDefault(); to your event bindings.
check the jsFiddle

It depends on model of your keyboard. Some keyboards doesn't work with some key combinations. It's normal.

Related

How to prevent default event for all cases of switch instruction

When dealing with a lot of possible keyCode (ex : for hotkeys), we'd like to use a switch statement.
We don't want to prevent all combinations of Ctrl + another key to preserve other constructor hotkeys.
We'd like to prevent the default action only for defined cases. But how to do that once ?
I think I'm missing something really obvious.
document.addEventListener("keydown", function(e) {
var key = e.keyCode || e.which;
if (!e.ctrlKey) return false;
switch(key) {
case 109: e.preventDefault(); scale(-1); break;
case 107: e.preventDefault(); scale(1); break;
case 96: e.preventDefault(); scale(0);break;
case 78: e.preventDefault(); newFile();break;
case 79: e.preventDefault(); openFile();break;
case 80: e.preventDefault(); printFile();break;
case 83: e.preventDefault(); saveFile();break;
case 66: e.preventDefault(); command("bold");break;
case 73: e.preventDefault(); command("italic");break;
case 85: e.preventDefault(); command("underline");break;
case 76: e.preventDefault(); command("justifyLeft");break;
case 69: e.preventDefault(); command("justifyCenter");break;
case 82: e.preventDefault(); command("justifyRight");break;
case 74: e.preventDefault(); command("justifyFull");break;
case 90: e.preventDefault(); clipboard.undo();break;
case 89: e.preventDefault(); clipboard.redo();break;
default: console.log("Key pressed n°", key)
}
}, false);
You can simply use a variable prevent that is only set to true in the default case. Then do e.preventDefault() after the switch statement, as follows:
document.addEventListener("keydown", function(e) {
var key = e.keyCode || e.which;
if (!e.ctrlKey) return false;
var prevent = true;
switch(key) {
case 109: scale(-1); break;
case 107: scale(1); break;
case 96: scale(0);break;
case 78: newFile();break;
case 79: openFile();break;
case 80: printFile();break;
case 83: saveFile();break;
case 66: command("bold");break;
case 73: command("italic");break;
case 85: command("underline");break;
case 76: command("justifyLeft");break;
case 69: command("justifyCenter");break;
case 82: command("justifyRight");break;
case 74: command("justifyFull");break;
case 90: clipboard.undo();break;
case 89: clipboard.redo();break;
default: prevent = false; console.log("Key pressed n°", key); break;
}
if (prevent) e.preventDefault();
}, false);

Add pause key in a game javascript

I create little game but I have some trouble to put a pause key. It doesn't work. Can you see what is wrong and correct me? Thanks. I would like to know how to implement a pause key and a key for restart for not refresh the page for do it.
Link of the game
code:
//this is where the keybinding occurs
$(document).keydown(function(e){
if(!gameOver && !playerHit){
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
}
Keys down:
switch(e.keyCode){
case 75: //this is shoot (k)
//shoot missile here
var playerposx = $("#player").x();
var playerposy = $("#player").y();
var name = "playerMissle_"+Math.ceil(Math.random()*1000);
$("#playerMissileLayer").addSprite(name,{animation: missile["player"], posx: playerposx + 90, posy: playerposy + 14, width: 36,height: 10});
$("#"+name).addClass("playerMissiles")
break;
case 65: //this is left! (a)
$("#playerBooster").setAnimation();
break;
case 87: //this is up! (w)
$("#playerBoostUp").setAnimation(playerAnimation["up"]);
break;
case 68: //this is right (d)
$("#playerBooster").setAnimation(playerAnimation["booster"]);
break;
case 83: //this is down! (s)
$("#playerBoostDown").setAnimation(playerAnimation["down"]);
break;
Pause key P:
case 80: //pause (p)
pauseGame();
alert ("paused")
}
}
});
Key released:
//this is where the keybinding occurs
$(document).keyup(function(e){
if(!gameOver && !playerHit){
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
switch(e.keyCode){
case 65: //this is left! (a)
$("#playerBooster").setAnimation(playerAnimation["boost"]);
break;
case 87: //this is up! (w)
$("#playerBoostUp").setAnimation();
break;
case 68: //this is right (d)
$("#playerBooster").setAnimation(playerAnimation["boost"]);
break;
case 83: //this is down! (s)
$("#playerBoostDown").setAnimation();
break;
case 80: //pause (p)
pauseGame();
}
}
});
Pause function:
function Pause () {
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(gameLoop, 1000 / 30);
gamePaused = false;
}};
Try and check if the P key is registered at all (using alert or a console message).
Then
I would also suggest the following: do not set the actual gameloop interval (or call game functions) inside the keyUp / keyDown handlers. Place actual game code inside their own functions, for example:
bGamePaused = false;
// key handlers
$(document).keydown(function(e){
switch(e.keyCode){
case 80:
// check if the key is registered
console.log("p is pressed, pause the game!");
// toggle the paused status:
bGamePaused = !bGamePaused;
// tell gameQuery to pause or resume the game
(bGamePaused) ? pauseGame() : resumeGame();
break;
}
$(document).keyup(function(e){
switch(e.keyCode){
// do not check for pause here. you only need to check when the key is either pressed or released, or the function will get called twice.
}

How do I best combine directional movements (up and left, up and right...) when moving objects?

I am using EaselJS in Javascript and I am using the keydown and keyup events to catch keyboard input (see below):
/*Connecting keydown input to keyPressed handler*/
this.document.onkeydown = keyPressed;
/*Connecting key up event to keyUp handler*/
this.document.onkeyup = keyUp;
And I have the following code to capture when up down, left and/or right are pressed, and to react to them temporarily. The movement is very shabby now, and I'm still trying to refine it. For me to be able to move my object correctly, I should be able to catch angle changes (left/right) and acceleration (forward) simulataneously.
Here is the keyDown code I have currently:
/*Keyboard input handlers - keydown and keyup*/
function keyPressed(event){
if(!event){ var event = window.event; }
switch(event.keyCode){
case KEYCODE_LEFT:
console.log("left held");
ellip.x -= 5;
break;
case KEYCODE_RIGHT:
console.log("right held");
ellip.x += 5;
break;
case KEYCODE_UP:
console.log("up held");
ellip.y -= 5;
break;
case KEYCODE_DOWN:
console.log("down held");
ellip.y += 5;
break;
}
}
Now notice in the console that hitting two of the arrow buttons does not yield combinations of messages (eg. up held and right held)
How do I go about dealing (or listening) to multiple events?
Here is a Fiddle! use the up, down, left and right arrows to move the red blotch around.
The way to handle this would be to capture which keys are down in your keyDown code and then do the movement itself in the handleTick function. You'll need to look at keyUp too so you know when the key is no longer down:
/*Keyboard input handlers - keydown and keyup*/
var left,
right,
up,
down;
function keyPressed(event){
if(!event){ var event = window.event; }
switch(event.keyCode){
case KEYCODE_LEFT:
console.log("left held");
left = true;
break;
case KEYCODE_RIGHT:
console.log("right held");
right = true;
break;
case KEYCODE_UP:
console.log("up held");
up = true;
break;
case KEYCODE_DOWN:
console.log("down held");
down = true;
break;
}
}
function keyReleased(event){
if(!event){ var event = window.event; }
switch(event.keyCode){
case KEYCODE_LEFT:
console.log("left released");
left = false;
break;
case KEYCODE_RIGHT:
console.log("right released");
right = false;
break;
case KEYCODE_UP:
console.log("up released");
up = false;
break;
case KEYCODE_DOWN:
console.log("down released");
down = false;
break;
}
}
function handleTick(event){
/*Scaling down the image*/
ellip.scaleX = 0.10;
ellip.scaleY = 0.10;
if(left) {
ellip.x -= 5;
} else if(right) {
ellip.x += 5;
}
if(up) {
ellip.y -= 5;
} else if(down) {
ellip.y += 5;
}
if (ellip.x > stage.canvas.width) {
ellip.x = stage.canvas.width;
}
stage.update();
}
EDIT: forked fiddle with this in action: http://jsfiddle.net/t2M82/

How to combine key codes to work together in javascript

E.g. I have the following script
<script>
document.onkeydown = function(evt){
evt = evt || window.event;
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
};
</script>
When I press
shift + keycode
to call a function specified, I am just new to JavaScript and I code JavaScript based on other languages I know
Thanks and Regards
Check .shiftKey which returns a boolean indicating if the key is pressed. Placing this conditional around your switch will prevent any events from occurring unless the key is pressed in combination with shift.
document.onkeydown = function(evt){
evt = evt || window.event;
if(evt.shiftKey){
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
}
};
You can detect the shift key separately. e.g. if you want to call createNewFile with the shift key down:
if(evt.shiftKey && evt.keyCode == 67) {
createNewFile();
}
In your code, you could do something like:
evt = evt || window.event;
switch (evt.keyCode){
case 67:
if (evt.shiftkey) {
// Do something special for shift mode.
} else {
createNewFile();
}
break;
...

JQuery while keydown

How can i make a movement of a element while the user is "keydown" and then if he make "keyup" to stop the animation(movement), this is my code by now
$(document).ready(function(){
function checkKey(e){
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keydown (checkKey);
} else {
$(document).keydown (checkKey);
}
})
i want to move the cube while the user press the key (down, left, up, right), not with every press, is possible?
You need a simple 2D engine that will setup a game loop.
Simple demo: http://jsfiddle.net/kzXek/
Source: https://github.com/superrob/simple-2D-javascript-engine/blob/master/simple2d.html
Is that you are looking for?
$(document).on("keyup", function() {
$("#cube").stop(true);
});
DEMO: http://jsfiddle.net/LjGRe/
you can just change the checkKey function, and add this to it :
function checkKey(e){
$(document).keyup(return);
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
I think using a timer to handle the animation is better.
You just start the timer when a key is pressed and stop it when the key is released ..
Here is a simple solution that handles multiple keypresses (can move diagonally)
var direction = {top:0,left:0},
animator = null,
cube = $("#cube");
function animate(){
cube.css({
top: '+=' + direction.top,
left: '+=' + direction.left
});
}
function setProperties(keyCode, unset){
switch (keyCode) {
case 40:
direction.top = (unset)?0:2;
break;
case 38:
direction.top = (unset)?0:-2;
break;
case 37:
direction.left = (unset)?0:-2;
break;
case 39:
direction.left = (unset)?0:2;
break;
}
}
function setKey(e) {
setProperties(e.keyCode);
if (animator === null){
animator = setInterval(animate, 10);
}
}
function unsetKey(e){
setProperties(e.keyCode, true);
if (direction.top === 0 && direction.left === 0){
clearTimeout(animator);
animator = null;
}
}
$(document)
.on("keyup", unsetKey)
.on('keydown', setKey);
Demo at http://jsfiddle.net/gaby/Cu6nW/

Categories

Resources