id = window.setInterval("animate();", 100); | A rather rare, but still used, DHTML scenario is not only positioning an element, but also moving and therefore animating an element. To do so, window.setTimeout() and window.setInterval() come in handy. The following code animates an ad banner diagonally over the page. The only potential issue is how to animate the position. For the Internet Explorer properties (posLeft, posTop), just adding a value suffices. For left and top, you first have to determine the old position and then add a value to it. The JavaScript function parseInt() exTRacts the numeric content from a string like "123px". However, parseInt() returns NaN if no value is found in left or top. Therefore, the following helper function takes care of this situation; in this case, 0 is returned instead: function myParseInt(s) { var ret = parseInt(s); return (isNaN(ret) ? 0 : ret); } Then, the following code animates the banner and stops after 50 iterations: Animating an Element (animate.html; excerpt) <script language="JavaScript" type="text/javascript"> var nr = 0; var id = null; function animate() { nr++; if (nr > 50) { window.clearInterval(id); document.getElementById("element").style.visibility = "hidden"; } else { var el = document.getElementById("element"); el.style.left = (myParseInt(el.style.left) + 5) + "px"; el.style.posLeft += 5; el.style.top = (myParseInt(el.style.top) + 5) + "px"; el.style.posTop += 5; } } window.onload = function() { id = window.setInterval("animate();", 100); }; </script> <h1>My Portal</h1> <div style="position: absolute; background-color: #eee; border: 1px solid"> JavaScript Phrasebook </div> | |