Home > OS >  Move square to right on every click
Move square to right on every click

Time:01-22

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

CodePudding user response:

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>

  •  Tags:  
  • Related