Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda