Even while pressing multiple keys, each keydown
and keyup
trigger an event.
So what you can do is to have a keys
map object which stores what keys are being pressed at the moment when a new keydown
event happens.
Have updated your code. It works now.
<body>
<div><img id = "player" src="https://i.ibb.co/3zzPvKT/Annoying-Dog-sprite.png"></div>
</body>
<script>
var frame = 0;
var y = 6;
var x = 453;
var facingleft = true;
var facingright = false;
var keys = {};
document.addEventListener("keyup", (e) => {
keys[e.keyCode] = false;
});
document.addEventListener("keydown", (e) => {
keys[e.keyCode] = true;
if (keys[37]) {
frame++;
x -= 5;
player.style.left= (x) + "px";
if (frame == 1) {
player.src = 'https://i.ibb.co/0t55kL0/doggo-00.png';
}
if (frame == 2) {
player.src = 'https://i.ibb.co/Y3q13J6/doggo-01.png';
}
if (frame == 3) {
frame = 1;
player.src = 'https://i.ibb.co/0t55kL0/doggo-00.png';
}
}
if (keys[39]) {
x += 5;
frame++;
player.style.left = (x) + "px";
if (frame == 1) {
player.src = 'https://i.ibb.co/NLHJBnJ/doggo-02.png';
}
if (frame == 2) {
player.src = 'https://i.ibb.co/N135wtG/doggo-03.png';
}
if (frame == 3) {
frame = 1;
player.src = 'https://i.ibb.co/NLHJBnJ/doggo-02.png';
}
}
if (keys[40]) {
if (y > 200) {
player.style.top = (y);
}
if (y < 200) {
y += 5;
player.style.top = (y) + "px";
}
}
});
</script>