cevilio

Bouncing object

Jul 6th, 2018
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html>
  2.     <head>
  3.         <title>Animation with Javascript, HMTL and CSS</title>
  4.  
  5.         <style>
  6.             .container {
  7.                 width: 90%;
  8.                 height: 90%;
  9.                 background-color: azure;
  10.                 margin: auto;
  11.                 margin-top: 5%;
  12.             }
  13.  
  14.             .object {
  15.                 width: 23px;
  16.                 height: 23px;
  17.                 background-color: coral;
  18.                 position: relative;
  19.                 left: 0;
  20.             }
  21.         </style>
  22.     </head>
  23.     <body>
  24.         <div class="container" id="container">
  25.             <div class="object" id="object" onclick="move()"></div>
  26.         </div>
  27.         <span id="tracker"></span>
  28.     </body>
  29.  
  30.     <script>
  31.         var pos = 0;
  32.         var direction = -1;
  33.  
  34.         function animate() {
  35.                 right_edge = document.getElementById("container").offsetWidth;
  36.                 if (pos >= right_edge-23 || pos <= 0 ) {
  37.                     direction *= -1;
  38.                 }
  39.                 pos += direction * 10;
  40.  
  41.                 document.getElementById("object").style.left = pos;
  42.                 document.getElementById("tracker").innerHTML = direction + " - " + pos;
  43.         }
  44.  
  45.  
  46.        
  47.         function move() {
  48.             setInterval(animate, 50);
  49.            
  50.         }
  51.     </script>
  52.  
  53. </html>
Advertisement
Add Comment
Please, Sign In to add comment