1
 function control()
            {
                var ship = document.getElementById("ship");
                document.onkeydown = function(e) { 
                    switch (e.keyCode) { 
                        case 38: 
                            ship.style.top += "5%"; 
                            break;
                        case 40: 
                            ship.style.top -= "5%"; 
                            break;
                        default:
                            break;
                    } 
                }
            }
setInterval(control,1000);

This code is not working.

The object I'm trying to move is not moving when I'm pressing the Up & Down Arrow Key.

2 Answers2

1

You can't do

ship.style.top += "5%"; 

because ship.style.top value is not a number but a string. the += opérator is concatening strings here.

Florent
  • 436
  • 3
  • 8
0

You should do something like that:

const ship = document.getElementById("ship");
document.onkeydown = function (e) {
    let winHeigth = window.innerHeight;
    let top = ship.style.top;
    switch (e.code) {
        case "ArrowUp":
            ship.style.top = (Number(top.substring(0, top.length - 2)) - (winHeigth / 20)) + "px";
            break;
        case "ArrowDown":
            ship.style.top = (Number(top.substring(0, top.length - 2)) + (winHeigth / 20)) + "px";
            break;
        default:
            break;
    }
}

The position attribute of the "ship" must be like "relative". By the way, e.keyCode is deprecated, you can use e.code instead ^^

Akif
  • 7,098
  • 7
  • 27
  • 53
Maxi_Mega
  • 16
  • 1
  • 4