I want to move snake left and right, it moves to the right direction well but when i click left it just stops and does not move left, i know that setInterval returns id but why does not it moves right ?
const snake = document.querySelector(".box");
const btns = document.querySelectorAll(".btns > button");
var X = 0;
var intervalrightId;
var intervallefttId;
btns.forEach((btn) => {
btn.addEventListener("click", function(e) {
if (e.target.textContent == "right") {
if (intervallefttId) {
clearInterval(intervallefttId)
}
intervalrightId = setInterval(() => {
X += 100;
snake.style.left = X;
}, 500)
}
if (e.target.textContent == "left") {
if (intervalrightId) {
clearInterval(intervalrightId)
}
intervallefttId = setInterval(() => {
X -= 100;
snake.style.right = X;
}, 500)
}
})
})
2
Answers
Both styles
left
andright
are conflicting.Pressing right, and then pressing left, leads to situation like that:
Which doesn’t make sense. You should rely on
left
ORright
instead bothUse transform property instead of left and right properties.
replace
snake.style.right = X;
by
snake.style.transform= 'translateX({X}px)
When you use left and right properties DOM object is positioned by distance to left or right of parent object (plus object should have position property set to absolute, otherwise left and right properties will not have effect). For example if parent objects is 100px wide and you set its childs left property to 10px, child child will be positioned 10xp right to parents left border and when you set right property to 10px, child will be positioned 10px left of right border of parent. And if your object has both right and left properties at the same time, one of them will be ignored. Thats why using transform propery to move object respective to its previous position is better choise.