cevilio icon

Bouncing object

cevilio | PRO | 07/07/18 01:57:37 AM UTC | 0 ⭐ | 298 👁️ | Never ⏰ | []
JavaScript |

2.5 KB

|

None

|

0 👍

/

0 👎

<!--
    this example is written by: vchar
    on Sat, 7 July 2018
-->
 
<html>
    <head>
        <title>Animation with Javascript, HMTL and CSS</title>
 
        <style>
            .container {
                width: 90%;
                height: 90%;
                background-color: azure;
                margin: auto;
                margin-top: 5%;
            }
 
            .object {
                width: 23px;
                height: 23px;
                background-color: coral;
                position: relative;
                left: 0;
            }
        </style>
    </head>
    <body>
        <div class="container" id="container">
            <div class="object" id="object" onclick="start()"></div>
        </div>
        <span id="tracker"></span>
    </body>
 
    <script>
 
        var h_pos = 0;          // horizontal position
        var v_pos = 0;          // vertical position
        var h_direction = -1;   // horizontal direction
        var v_direction = -1;   // vertical direction
 
        // get the right edge of a container
        var right_edge = document.getElementById("container").offsetWidth;
        // get the bottom edge of a container
        var bottom_edge = document.getElementById("container").offsetHeight;
 
        // this function control the animation an object by linearly moving it 
        // all directions such as up, down, left, right
        function animate() {
                if (h_pos >= right_edge-23 || h_pos <= 0 ) {
                    h_direction *= -1;
                }
 
                if (v_pos >= bottom_edge-23 || v_pos <= 0) {
                    v_direction *= -1;
                }
 
                h_pos += h_direction * 1;
                v_pos += v_direction * 1;
 
                move(h_pos, v_pos);
                track(h_pos, v_pos, h_direction, v_direction);
        }
 
        // move an object base on a given position
        function move(x, y) {
            document.getElementById("object").style.left = x;
            document.getElementById("object").style.top = y;
        }
 
        // track an object's position
        function track(x, y, x_direction, y_direction) {
            document.getElementById("tracker").innerHTML = 
                x_direction + " - " + y + " - " + y_direction + " - " + x;
        }
 
        // start the animation
        function start() {
            setInterval(animate, 1);    // time interval in milisecon(s)
        }
    </script>
 
</html>

Comments