Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
How to move a square back and forth

I am trying to make a square move back and forth by pressing a button one time with javascript. I can make it move to the right edge but don't know how to make it move back again. Help appreciated.

function myMove() {
  let id = null;
  const elem = document.getElementById("animate");   
  let pos = 0;
  clearInterval(id);
  id = setInterval(frame, 5);
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++; 
      elem.style.left = pos + "px"; 
    }
  }
}
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
<body>
<p><button onclick="myMove()">Click Me</button></p> 

<div id ="container">
  <div id ="animate"></div>
</div>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I know you are asking for a javascript-based solution, but it's worth noting that this kind of presentation can be achieved with CSS alone.

So, for the sake of completeness, I am posting a CSS-only solution below.

N.B. There is a key difference between what CSS is capable of and what JS is capable of.

Note that in the CSS-only example below, each time you click the button, you will then have to click outside the button before the button will work again.


CSS-only Working Example:

.move-square-button {
  display: block;
  margin-bottom: 12px;
  cursor: pointer;
}

.container {
  width: 400px;
  height: 144px;
  position: relative;
  background-color: yellow;
}

.square {
  position: absolute;
  top: 0;
  left: 0;
  width: 50px;
  height: 50px;
  background-color: red;
  transform: translateX(0);
}

.move-square-button:focus {
  cursor: not-allowed;
}

.move-square-button:focus + .container .square {
  animation: moveSquareRightThenLeft 2s linear;
}

@keyframes moveSquareRightThenLeft {
  50% { transform: translateX(calc(400px - 100%)); }
}
<button class="move-square-button" type="button">Click Me</button> 

<div class="container">
  <div class="square"></div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Not the prettiest solution but shoud do the trick. Essentially if the rectangle reaches the right edge the "inverseDirection" variable inverts from false to true and therefore the pos variable decrements instead of increment. The opposite happens in the left edge.

function myMove() {
  let id = null;
  const elem = document.getElementById("animate");   
  let pos = 0;

  let inverseDirection = false;

  clearInterval(id);
  id = setInterval(frame, 5);
  function frame() {
    if (pos === 350 && !inverseDirection) {
      inverseDirection = true;
    }else if(pos === 0 && inverseDirection){
      inverseDirection = false;
    }
    pos = (inverseDirection) ? pos-1 : pos+1; 
    elem.style.left = pos + "px"; 
  }
}
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
<p><button onclick="myMove()">Click Me</button></p> 

<div id ="container">
  <div id ="animate"></div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

whenever you are calling the myMove function it has pos set to 0. you should calculate position on the fly, and based on that logic you will be moving it right or left. assume the length is 350, you can do something like this:

function myMove() {
  let id = null;
  const elem = document.getElementById("animate");   
  let pos = elem.offsetLeft;
  let dir = "";
  if(pos === 0) {
    dir = "right";
  } else {
    dir = "left";
  }
  clearInterval(id);
  id = setInterval(frame, 5);
  function frame() {
    if (pos == 350 && dir == "right") {
      clearInterval(id);
    } if (pos == 0 && dir == "left") {
      clearInterval(id);
    } else if(dir === "right") {
      pos++; 
      elem.style.left = pos + "px"; 
    } else if(dir === "left") {
      pos--; 
      elem.style.left = pos + "px"; 
    }
  }
}
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
<body>
<p><button onclick="myMove()">Click Me</button></p> 

<div id ="container">
  <div id ="animate"></div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda