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

99
Vistas
Move square to right on every click

As I wrote in the title, when user clicks on the square it should move 100px to the right and after next click it should move 100px again to the right but square is going back to left. How can I fix this?

Also in JSFiddle code is working but when I open this on Chrome it's giving me error:
Cannot read properties of null (reading 'addEventListener')

<html>
<head>
    <title>JavaScript animation</title>
    <style>
        #square {
            width: 100px;
            height: 100px;
            background-color: #333;
            position: absolute;
            left: 0px;
            top: 100px;

            transition-duration: 3s;
            transition: left 1.5s ease-in-out;
        }

        #square.active {
            left: calc(100px);
            transition: left 1.5s ease-in-out;
        }
    </style>
    <script>
        const square = document.querySelector('#square');

        square.addEventListener('click', toggleActive);

        function toggleActive() {
            square.classList.toggle('active');
        }
    </script>
</head>
<body>
    <div id="square"></div>
</body>
</html>

JS Fiddle link

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Right now you're simply toggling the class, so it moves right and back to its original position.

You need to add a value to the already existing value, in this case 100 pixels.

Also not getting an error from your original fiddle.

const square = document.querySelector('#square');

square.addEventListener('click', moveRight);

function moveRight() {
  square.style.left = square.offsetLeft + 100+'px';
}
#square {
  width: 100px;
  height: 100px;
  background-color: #333;
  position: absolute;
  left: 0px;
  top: 100px;
  transition-duration: 3s;
  transition: left 1.5s ease-in-out;
}
<div id="square"></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