I have a web page with a snake that the user should control with buttons.
I used a for
loop to bind the click event to the buttons. The move should happen in the if
statement, but the snake does not move.
Why does it not work?
const squares = document.querySelectorAll(".square");
const snake = document.querySelector(".snake");
const btns = document.querySelectorAll(".btns > button");
var x = 0;
var y = 0;
for (var i = 0; i < btns.length; ++i) {
btns[i].addEventListener("click", function(e) {
x += 100;
if(e.target.innerHTML.trim() === "right") {
snake.style.left = x;
}
});
}
.snake { display: inline-block; position: absolute; border: 1px solid }
<div class="btns"><button class="button">right</button></div>
<div class="snake">SNAKE</div>