Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!