skip to Main Content

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


  1. Both styles left and right are conflicting.
    Pressing right, and then pressing left, leads to situation like that:

    <div class="box" style="left: 100px; right: 200px;"/>
    

    Which doesn’t make sense. You should rely on left OR right instead both

    Login or Signup to reply.
  2. Use 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search