document.geteElementById(“player”) not working

  Kiến thức lập trình

when i try to move the “player” with arrows it says uncaught typeError and says that the player got with getElementById its a null
html

    <link rel="stylesheet" href="Style.css">
    <script src="game_2d.js"></script>
</head>
<body>
<div id="player"><img src="player_test.png" alt=""></div>

css

#player{position: absolute;
top: 0;
left: 0;
width: 500px;
height: 500px;
}

javascript

const player = document.getElementById("player")
const moveAmount = 10
let x = 0
let y = 0

document.addEventListener("keydown", event =>{
    if(event.key.startsWith("Arrow")){

        switch(event.key){
            case "ArrowLeft":
                x -= moveAmount
                break

            case "ArrowRight":
                x += moveAmount
                break 
        }
        player.style.top = `${y}px`
        player.style.left = `${x}px`
    }
})

i copy the code from this video:https: //www.youtube.com/watch?v=q32skvBgxo4&t=218s

New contributor

Mateo Flammini is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT