I have tried many other solutions on this problem but none of them are working. I checked my code from other questions I found and it seems to be perfectly fine. I want the javascript to move the div called "snake" in what direction it is moving. But it keeps saying that snake is "null". Code:
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<style>
#main {
height: 100px;
width: 100px;
border: 1px solid black;
}
#snake {
position: absolute;
top: 20px;
left: 20px;
width: 10px;
height: 10px;
background: black;
}
</style>
<script src="script.js"></script>
</head>
<body>
<div id="main">
<div id="snake"></div>
</div>
</body>
</html>
Javascript:
let movePos = null;
let isMoving = false;
let snake = document.getElementById("snake");
function main() {
document.addEventListener("keypress", function(event) {
if (event.key == "w") {
movePos = "up";
} else if (event.key == "s") {
movePos = "down";
} else if (event.key == "a") {
movePos = "left";
} else if (event.key == "d") {
movePos = "right";
}
if (!isMoving) {
askToMove();
}
});
}
function askToMove() {
if (movePos != null) {
isMoving = true;
setInterval(move, 1000);
}
}
function move() {
if (movePos == "up") {
snake.style.top = 100;
}
}
main();
`, or leave it where it is and add `defer` attribute to the script tag.
– connexo Mar 09 '21 at 12:44