N
N
Nora2021-07-05 21:48:25
JavaScript
Nora, 2021-07-05 21:48:25

How to make animation in js back and forth?

How to make the plane fly back and forth?
The code is written in one direction, but I don’t understand how to the other

<code lang="css">
<style>
      img{
        position:absolute;
        width: 220px;
        transform: scale(-1,1);
      }
    </style>
</code>
  </head>
  <body>
    <img src="/img/самолет.png" id="plane" alt="">
<code lang="javascript">
    <script>
      let plane = document.getElementById("plane");
      let n = 0;
      function movePlane(){
        n = n + 1;
        plane.style.left = n+"px";
      }
      setInterval(movePlane, 10);
    </script>
</code>
  </body>
</html>

noradrzo.beget.tech/plane.html

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Azasemey, 2021-07-06
@Azasemey

<script>
          const plane = document.getElementById("plane");
          let n = 0;
          const maxTravel = window.outerWidth-plane.offsetWidth;
          let direction = 0;
          plane.style.left = "";
         function movePlane(){     
            if(n < maxTravel  && direction === 0)  {    
            n++;
            plane.style.left = `${n}px`; 
            plane.classList.remove('reverse') 
            }else {
                direction = 1;
                n--
                plane.style.left = `${n}px`
                plane.classList.add('reverse')
            };
            if(n<0){
                direction = 0;
            }
          };
          setInterval(movePlane,   5);
        </script>

honestly not sure if this is the right solution, but it works xD

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question