Image change on pressing keyup and keydown - javascript

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">

Related

JavaScript page causes computer to become unresponsive

I am completely new to JavaScript so please be patient with me
I have been following a tutorial to display images from a folder in JavaScript but when I add the script that iterates it causes the computer viewing the page to lock up completely
The following in inside my tags:
var canvas = document.getElementById("canvas");
var graphics_context = canvas.getContext("2d");
var rightPressed = false;
var leftPressed = false;
var currentpage = 0;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if ((e.key == "Right" || e.key == "ArrowRight") && !rightPressed) {
rightPressed = true;
currentpage++;
}
else if ((e.key == "Left" || e.key == "ArrowLeft") && !leftPressed) {
leftPressed = true;
currentpage--;
}
}
function keyUpHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
rightPressed = false;
}
else if (e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
}
function draw() {
var img = new Array();
for(let i = 0; true; i++) {
try {
var image = new Image();
image.src = "img/" + i + ".jpg";
img[i] = image;
}
catch(err) {
break;
}
}
if(currentpage <= 0)
currentpage = 0;
if(currentpage >= img.length)
currentpage = img.length - 1;
ctx.drawImage(img[currentpage], 0, 0, 800, 800);
}
setInterval(draw, 10);
I do realise that reading from a folder in a loop is incredibly inefficient but I really don't see how it would cause my entire PC to lock up (it is a separate PC to the one running the page)
Any help is appreciated!

cancel an if statement if another statement comes true

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

Simple move javascript game

what wrong with my code
function move(x,y)
{
setInterval(function()
{
gameArea.clear();
gamePiece.x += x;
gamePiece.y += y;
gamePiece.update();
}, 100);
}
document.getElementsByTagName('body')[0].onkeyup = function(e)
{
var myInterval;
if(e.keyCode == 37)
{
move(10,0);
}
else if(e.keyCode == 38)
{
move(0,-10);
}
else if(e.keyCode == 39)
{
move(-10,0);
}
else if(e.keyCode == 40)
{
move(0,10);
}
}
This produce output i'm not expected, and the object can't move correctly.
Please help me to fixed this.

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/

capturing simultaneous left and right mouse button clicks in javascript

What is the best way to capture a left AND right mouse click in javascript? I'm not using jQuery (it's next on my to-learn list), just javascript for now. Basically, I want to do something like
onClick()=javascript:rightClickFunction() // do right click function
onContextMenu()=javascript:leftClickFunction() /
onBoth() ???
The only thing I could find on stackoverflow was:
How to distinguish between left and right mouse click with jQuery
How should I capture the double-button click? Can i check if the opposite button is also clicked during the R and L button routines?
You could track which mouse buttons are down with some boolean variables like this:
var leftButtonDown = false;
var rightButtonDown = false;
$(document).mousedown(function() {
if(e.which == 1) {
leftButtonDown = true;
} else if (e.which == 3) {
rightButtonDown = true;
}
});
$(document).mouseup(function() {
if(e.which == 1) {
leftButtonDown = false;
} else if (e.which == 3) {
rightButtonDown = false;
}
});
$(document).click(function() {
if(leftButtonDown && rightButtonDown) {
// left and right buttons are clicked at the same time
}
});
If both booleans are true, the right and left mouse buttons are both being clicked.
Pure Javascript solution based on the answer by Elliot:
var leftButtonDown = false;
var rightButtonDown = false;
document.addEventListener("mousedown", function () {
if (e.which == 1) {
leftButtonDown = true;
} else if (e.which == 3) {
rightButtonDown = true;
}
});
document.addEventListener("mouseup", function () {
if (e.which == 1) {
leftButtonDown = false;
} else if (e.which == 3) {
rightButtonDown = false;
}
});
document.addEventListener("click", function () {
if (leftButtonDown && rightButtonDown) {
// Click with both LMB and RMB.
}
});
For anyone still interested in a recent answer, as event.which is deprecated you can use the following code with ES6 syntax.
let leftButtonDown = false;
let rightButtonDown = false;
document.addEventListener("mousedown", (e) => {
// left click
if (e.button === 0) {
leftButtonDown = true;
}
// right click
if (e.button === 2) {
rightButtonDown = true;
}
if (leftButtonDown && rightButtonDown) {
// insert code here
}
});
document.addEventListener("mouseup", (e) => {
if (e.button === 0) {
leftButtonDown = false;
}
if (e.button === 2) {
rightButtonDown = false;
}
});
If you want to prevent the context menu from popping up you can try a variation of this:
let leftButtonDown = false;
let rightButtonDown = false;
document.addEventListener("mousedown", (e) => {
// left click
if (e.button === 0) {
leftButtonDown = true;
}
// right click
if (e.button === 2) {
rightButtonDown = true;
}
if (leftButtonDown && rightButtonDown) {
// insert code here
}
});
document.addEventListener("mouseup", (e) => {
if (e.button === 0) {
leftButtonDown = false;
}
});
document.addEventListener("contextmenu", (e) => {
if (leftButtonDown && rightButtonDown) {
e.preventDefault();
}
rightButtonDown = false;
});
Modern browsers mouse buttons mapping:
left click = 0
middle click = 1
right click = 2
IE8 and earlier mouse buttons mapping:
left click = 1
middle click = 4
right click = 2

Categories