cancel an if statement if another statement comes true - javascript

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;
}
}

Related

Why when I press two keys simultaneously and stop pressing one, the other stops working?

I am working with keyboard events in Javascript. My goal is to be able to move images on a canvas with the keyboard arrows, but there is a problem: when I press two keys simultaneously and then release one of them, the key I left pressed does not work, it crashes and therefore the image It does not move. I'm already using the keyup and keydown events and I managed to find a way to detect when two keys are pressed at the same time, however I can't solve this problem. Can anyone help me? Thank you.
this is what i tried
function keyPressed(event) {
keysPressed[event.key] = true;
switch(event.key) {
case 'ArrowLeft':
playerPetSelected.speedX = -5;
break;
case 'ArrowRight':
playerPetSelected.speedX = 5;
break;
case 'ArrowDown':
playerPetSelected.speedY = 5;
break;
case 'ArrowUp':
playerPetSelected.speedY = -5;
break;
}
if (keysPressed['ArrowLeft'] && event.key == 'ArrowDown') {
playerPetSelected.speedX = -3.5;
playerPetSelected.speedY = 3.5;
}
if (keysPressed['ArrowDown'] && event.key == 'ArrowLeft') {
playerPetSelected.speedY = 3.5;
playerPetSelected.speedX = -3.5;
}
if (keysPressed['ArrowLeft'] && event.key == 'ArrowUp') {
playerPetSelected.speedX = -3.5;
playerPetSelected.speedY = -3.5;
}
if (keysPressed['ArrowUp'] && event.key == 'ArrowLeft') {
playerPetSelected.speedY = -3.5;
playerPetSelected.speedX = -3.5;
}
if (keysPressed['ArrowUp'] && event.key == 'ArrowRight') {
playerPetSelected.speedY = -3.5;
playerPetSelected.speedX = 3.5;
}
if (keysPressed['ArrowRight'] && event.key == 'ArrowUp') {
playerPetSelected.speedX = 3.5;
playerPetSelected.speedY = -3.5;
}
if (keysPressed['ArrowDown'] && event.key == 'ArrowRight') {
playerPetSelected.speedY = 3.5;
playerPetSelected.speedX = 3.5;
}
if (keysPressed['ArrowRight'] && event.key == 'ArrowDown') {
playerPetSelected.speedX = 3.5;
playerPetSelected.speedY = 3.5;
}
}
function stopMovement(event) {
keysPressed[event.key] = false;
playerPetSelected.speedX = 0;
playerPetSelected.speedY = 0;
}
The parts where I modify the 'playerPetSelected' object are so that the images can be moved on the canvas.
I was hoping I wouldn't have this problem anymore because here I was able to find a way to detect when two keys are pressed at the same time, but it only helped me to manipulate the speed of movement on the canvas when two keys are pressed simultaneously.
Here is how I would do it... Using an object for the speed in x/y. Look how the conditions are easier to read. That handles all possible arrow combinations.
window.addEventListener("keydown", keyPressed)
window.addEventListener("keyup", keyUnpressed)
let keysPressed = {}
function keyPressed(event) {
keysPressed[event.key] = true
getActiveKeys()
}
function keyUnpressed(event) {
keysPressed[event.key] = false
getActiveKeys()
}
function getActiveKeys() {
const activeKeys = Object.keys(keysPressed).map((key) => keysPressed[key] ? key : null).filter((key) => key)
const speed = {
x: 0,
y: 0
}
if(keysPressed["ArrowUp"]){
speed.y = 5
}
if(keysPressed["ArrowDown"]){
speed.y = -5
}
if(keysPressed["ArrowLeft"]){
speed.x = -5
}
if(keysPressed["ArrowRight"]){
speed.x = 5
}
// Gas and break conditions
if(keysPressed["ArrowUp"] && keysPressed["ArrowDown"]){
speed.y = 0
}
if(keysPressed["ArrowLeft"] && keysPressed["ArrowRight"]){
speed.x = 0
}
// Diagonal condition
if(speed.x && speed.y){
speed.x *= 0.7
speed.y *= 0.7
}
document.querySelector("#activeKeys").innerText = JSON.stringify(activeKeys)
document.querySelector("#xSpeed").innerText = speed.x
document.querySelector("#ySpeed").innerText = speed.y
}
<div>Keys pressed: <span id="activeKeys">[]</span></div>
<div>Speed X: <span id="xSpeed">0</span></div>
<div>Speed Y: <span id="ySpeed">0</span></div>
Run that snippet in full page mode, else the page will scroll. Or look at CodePen

Image change on pressing keyup and keydown

I am new to JavaScript and this community. I apologize if this has been asked before, but the threads I found for this topic did not really help me with this specific problem.
I would like to achieve the following working:
Image 1 is displayed.
If you press the left arrow key (keydown) the image should change to image 2.
If you stop pressing (keyup), it should change to image 3.
If you press the right arrow key it should change to image 4 and on keyup, change to image 5.
The code is:
<img src="img/image1.png" id="myIMG">
and
var imgs = ["img/image5.png", "img/image3.png", "img/image1.png", "img/image4.png"];
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];
}
var keys = {};
$(document).keydown(function (event) {
keys[event.which] = true;
}).keyup(function (event) {
if(e.keyCode == 37){
delete keys[37];
changeIMG(+1);
}
else if(e.keyCode == 39){
delete keys[39];
changeIMG(+2);
}
});
function IMGLoop() {
if (keys[37]) {
changeIMG(+3);
} else if (keys[39]) {
changeIMG(+4);
}
setTimeout(IMGLoop, 20);
}
IMGLoop();
The issue is described below.
The keyup does not do anything and the keydown only works once and then I can not even switch between left and right anymore.
I need to do this with a loop because I also want to do other things on the loop that are not displayed in this code. I would appreciate any type of help.
Hope this helps you
var imgs = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQgz2HMpGysZL6ifYfhqWASDoA0b2MyX-gyMuQszgYRv87yr9qug",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQV3JL_HtVvlLr3Xy-KQV5MNmIF2-kCb9cHB4oXkUKQ1jiLT0H",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgDmo-5YpwYK9Yc35CK1oq3Y2zHDnXlu3q6m7GnSvLarDTRl0B",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQt2dZklq8eDbsNL1vZ0MTwZsm0KWDIxl6YifmbUqjPiE5lOmIe"
];
var showImageName = 2;
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[dir];
img.alt = dir;
}
var keyPressed = false;
function f(e) {
if (e.keyCode == 37) {
showImageName--;
if (showImageName == -1) {
showImageName = imgs.length - 1;
}
changeIMG(showImageName);
} else if (e.keyCode == 39) {
showImageName++;
if (showImageName == imgs.length) {
showImageName = 0;
}
changeIMG(showImageName);
}
}
$(document)
.keydown(function(e) {
if (!keyPressed) {
keyPressed = true;
f(e);
}
})
.keyup(function(e) {
if (keyPressed) {
keyPressed = false;
f(e);
}
});
changeIMG(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt='' src="" id="myIMG">
Update after question edited
var imgs = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQgz2HMpGysZL6ifYfhqWASDoA0b2MyX-gyMuQszgYRv87yr9qug",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQV3JL_HtVvlLr3Xy-KQV5MNmIF2-kCb9cHB4oXkUKQ1jiLT0H",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgDmo-5YpwYK9Yc35CK1oq3Y2zHDnXlu3q6m7GnSvLarDTRl0B",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQt2dZklq8eDbsNL1vZ0MTwZsm0KWDIxl6YifmbUqjPiE5lOmIe",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSnDWTv5oLaNgUm_SXQFSzzBJl-21c7wLCC6Hgld-ndQ1k0knly"
];
var showImageName = 2;
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[dir];
img.alt = dir;
}
var keyPressed = false;
function f(e, str) {
switch (str) {
case "up":
if (e.keyCode == 37) {
changeIMG(2);
} else if (e.keyCode == 39) {
changeIMG(4);
}
break;
case "down":
if (e.keyCode == 37) {
changeIMG(1);
} else if (e.keyCode == 39) {
changeIMG(3);
}
break;
}
}
$(document)
.keydown(function(e) {
if (!keyPressed) {
keyPressed = true;
f(e, "down");
}
})
.keyup(function(e) {
if (keyPressed) {
keyPressed = false;
f(e, "up");
}
});
changeIMG(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt='' src="" id="myIMG">

javascript keypress to control animation

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!

Javascript error: I have a unexpected end of input on my first line, with no apparent problems, but I'm getting a message and the whole canvas stops

I put in the entire thing just in case
I went into chrome and looked for errors, and it wasnt working either so I checked, apparently the first line has a problem. I kept the first 6 lines and deleted all else then it worked fine, so I went to SublimeText2 and searched for every ) and } in the code.
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasJet = document.getElementById('canvasJet');
var ctxJet = canvasJet.getContext('2d');
var jet1;
var fps = 17;
var drawInterval;
var imgSprite = new Image();
imgSprite.src = 'SpriteSheet.png'
imgSprite.addEventListener('load',init,false);
function init() {
drawBg();
startDrawing();
jet1 = new Jet();
document.addEventListener('keydown',checkKeyDown,false);
document.addEventListener('keyup',checKeyUp,false);
}
function draw() {
jet1.draw();
}
function startDrawing() {
stopDrawing();
drawInterval = setInterval(draw,fps);
}
function stopDrawing() {
clearInterval(setInterval);
}
Jet.prototype.draw = function() {
clearCtxJet();
ctxJet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
};
function Jet() {
this.srcX = 0;
this.srcY = 0;
this.drawX = 200;
this.drawY = 200;
this.width = 96;
this.height = 30;
}
function drawJet() {
}
function drawBg() {
ctxBg.drawImage(imgSprite,96,0,800,500,0,0,800,500)
}
function clearCtxBg() {
ctxBg.clearRect(0,0,800,500);
}
function clearCtxJet() {
ctxJet.clearRect(0,0,800,500);
}
function checkKeyDown(e) {
var keyID = (e.keyCode) ? e.keyCode : e.which;
if (keyID === 38) { // 38 is up key
alert('up arrow was pressed');
e.preventDeafault();
}
if (keyID === 39) { // 39 is right key
e.preventDeafault();
}
if (keyID === 40) { // 40 is down key
e.preventDeafault();
}
if (keyID === 37) { // 37 is left key
e.preventDeafault();
}
function checkKeyup(e) {
var keyID = (e.keyCode) ? e.keyCode : e.which;
if (keyID === 38) { // 38 is up key
alert('up arrow was pressed');
e.preventDeafault();
}
if (keyID === 39) { // 39 is right key
e.preventDeafault();
}
if (keyID === 40) { // 40 is down key
e.preventDeafault();
}
if (keyID === 37) { // 37 is left key
e.preventDeafault();
}
}
I assume you're showing only parts of the code so there's no way of knowing whether this is the actual error, but both checkKeyup and checkKeydown are missing closing braces.
I recommend installing Package Control for Sublime Text 2 and then using it to install SublimeLinter which will be able to check your code for you and point out missing semicolons and braces.
It would be nice to see full code in http://jsfiddle.net

Snake script is not passing values to variable

So here is my snake script -
http://jsfiddle.net/6bKHc/24/
I started to create a snake game, but basically move(top), move(bottom) e.c. is not working. Any ideas why? I understand that I can't pass the elements to variable like this, so maybe you could show me how to do that correctly?
Ok cleared syntax and took a look at errors this should get you started
$(document).keydown(function(event){
var move, inter;
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
if(dir == 'top') {
snake.stop().animate({"top": "+=5px"});
}
if(dir == 'bottom') {
snake.stop().animate({"top": "-=5px"});
}
if(dir == 'left') {
snake.stop().animate({"left": "+=5px"});
}
if(dir == 'right') {
snake.stop().animate({"top": "-=5px"});
}
}, 500);
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
}; });​
fiddle
Couple of obvious additions to make:
boundary checking
smoothness of animation.
To make it work you will have to moodify your code like follows :
$(document).keydown(function() {
var inter;
return function(event) {
var move, prevDirection;
clearInterval(inter);
inter = setInterval(move = function(direction) {
var value, prop;
switch (direction || prevDirection) {
case "top":
prop = "top";
value = -5;
break;
case "bottom":
prop = "top";
value = 5;
break;
case "left":
prop = "left";
value = -5;
break;
case "right":
prop = "left";
value = 5;
break;
}
if (direction) prevDirection = direction;
$(".snake").css(prop, $(".snake").position()[prop] + value);
}, 500);
if (event.which == 40) {
move('bottom');
} else if (event.which == 39) {
move('right');
} else if (event.which == 37) {
move('left');
} else if (event.which == 38) {
move('top')
};
}
}());​
​
http://jsfiddle.net/6bKHc/42/

Categories