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
Update after question edited