Don't just move it - animate it!

'Flying' objects onto the screen has long been a standard feature of presentation graphics software, and now you can do it on your Web page using Dynamic HTML.

The technique is simple. First, create your object (image, text-containing SPAN or whatever) in whatever position you want it to occupy after it's flown onto the screen. In this example the object is an image tag that's centred at the start of the page.

Next, add an inline style sheet to the object's HTML tag. The style sheet makes the object relatively-positioned, and gives it a starting position offset from the 'home' position where you've defined it. Calculate this position so that the object is initially off the screen. The inline style sheet for this page's image is:

style="position:relative;top:-150;left:-150;"

The negative pixel coordinates place it 150 pixels above and to the left of its true 'home' position, i.e. off the top edge of the browser screen (note - for more details of object positioning, see last month's Publish and be...)

When the page loads, the object isn't visible, but there's a 'hole' in the page where it will eventally come to rest. Now you need to move it, step by step, onto the screen.

When the page is loaded, the BODY section's 'onload' event calls a Javascript routine which sets up an interval timer. This might sound complex, but it's really quite simple - when you create an interval timer you're saying to the browser 'every n milliseconds, execute this specified JavaScript function, and keep on doing it until I tell you to stop, or the browser loads a different page'

The JavaScript routine executed by the interval timer in this page is called Movepic(). Each time it's executed, it moves the image diagonally towards its home position, by adding 10 to its left and top pixel coordinates. When the pixelLeft coordinate reaches zero the routine cancels the interval timer, so it doesn't get called again. The image then stops 'moving'. I've used a simple diagonal path for my animation, but you can build complex formulae that give objects irregular or wavy trajectories as they fly onto the screen.

The pushbutton repeats the animation process by first moving the image back to its original, off-screen location, then calling the same StartMove() routine as the BODY section's 'onload' event does. Note that the browser doesn't have to go back to the server at this point - it all happens locally, with no download delay.

Incidentally, if you're wondering why I don't use a simple JavaScript for.. loop to repeatedly change the pixel coordinates, click here to find out.

(Also incidentally, the hyperlink above targets different pages depending on whether you're using IE4 or not - another way of switching between IE4 and non-IE4 pages. To find out how it's done, view the source of this page, and load the two alternative target pages by switching browsers.)


Back to menu