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

102
Visualizações
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 Respostas
Responde à pergunta

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 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