Animate1 Example -- Source Code

HTML Page -- index.htm

<!DOCTYPE html>

<!-- Animate1 Example
Source code file: styles.css
Move a square along a straight 
line within the container -->

<html lang="en">
<head>
    <title>Animation1 Example</title>
    <script src="script.js"></script>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <h2>Animate1 Example</h2>

    <!-- Click button to run the animation. -->
    <p><button id="btn">
        Run Animation</button>
    </p>

    <!-- When button is clicked, the 
         square moves along a straight
         line within the container.-->
    <div id ="container">
        <div id ="square"></div>
    </div>
</body>
</html>

CSS Page -- styles.css

 /* Animate1 Example
   Source code file: styles.css
   Move a square along a straight 
   line within the container. */

#container {
    width: 400px;
    height: 400px;
    position: relative;
    background: yellow;
}

#square {
    width: 50px;
    height: 50px;
    left: 0px;
    top: 0px;
    position: absolute;
    background-color: red;
}

Script Page -- script.js

 // Animate1 Example
// Source code file: styles.css
// Move a square along a straight 
// line within the container.

var timer = null;
function moveSquare() {
    var elem = document.getElementById("square"); 
    var posx = 0;
    var posy = 0;
    clearInterval(timer);
    timer = setInterval(frame, 3);

    function frame() {
        if (posx == 350) {
            clearInterval(timer);
        } 
        else {
            posx += 1.0;
            posy += 0.5;
            elem.style.left = posx + "px"; 
            elem.style.top = posy + "px"; 
        }
    }
}

function init( ) {
    var button = document.getElementById("btn");
    button.addEventListener("click", moveSquare);
}

window.addEventListener("load", init);