Skip to content
Advertisement

Keyboard Arrow Key Controls in Javascript

 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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement