Animation

Animation effects can be created to move objects around the document

 

This example has a div with a few lines of html, that is styled by JavaScript, and then moves across the page upon the window loading and .onclick:

<html>
    <head>
        <title>JavaScript</title>
    </head>
    <body>
		<div id="theDiv">
			<h1>Here's mydiv!</h1>
			<p>First line of text.</p>
			<p>Second line of text.</p>
			<p>Third line of text.</p>
		</div>
        <script>
            var myDiv = document.getElementById("theDiv");

			myDiv.style.width="250px";
			myDiv.style.border="2px solid red";
			myDiv.style.backgroundColor="#ffff00";
			myDiv.style.textAlign="center";

			var currentPos = 0;

			var intervalHandle;

			function beginAnimate() {
				myDiv.style.position = "absolute";
				myDiv.style.left = "0px";
				myDiv.style.top = "100px";
				// call the animateBox function
				intervalHandle = setInterval(animateBox,20);
			}

			function animateBox() {
				// set new position
				currentPos+=5;
				myDiv.style.left = currentPos + "px";
				//
				if ( currentPos > 900) {
					// clear interval
					clearInterval(intervalHandle);
					// reset custom inline styles
					currentPos = 0;
					myDiv.style.position = "";
					myDiv.style.left = "";
					myDiv.style.top = "";

				}
			}
			window.onload =  function() {
				setTimeout(beginAnimate,1000);
			};

			myDiv.onclick =  function() {
				beginAnimate();
			};

        </script>
    </body>
</html>

Leave a Reply