free hosting   image hosting   hosting reseller   online album   e-shop   famous people 
Free Website Templates
Free Installer

Image Animation
Using CSS Position


This script lets you move an image across the page, using the CSS position attribute.

For more about the position parameter, see Image Layering Using Z-Index.


Paste the code below into the head section of your page:
This goes inside your body tag:
And this goes in the body of your page:

How It Works

The graphic is assigned some style sheet position properties inside its img tag:
<img src="image.jpg" border=1 id="pic"
style="position: relative; left: 50">
The graphic is also assigned an ID, pic.


When the Start button is clicked, the function move() is called.

The position of the image is incremented by a counter i, which moves it across the page:
pic.style.left=i
where:
  • pic is the ID of the image
  • style signifies that a style is to be applied
  • left is the style characteristic
  • i is the value for left
  • Left is number of pixels to the right of the graphic's actual left-hand side.

    If the true left-hand position is the left margin, its true left position is zero.

    If the left style attribute is applied, with a value of 50, its postion is now 50 pixels right of the margin.

    So:
  • the graphic's initial position is 50 pixels
  • the counter increments the left position value to make the image move
  • the counter limit - (document.body.clientWidth - 100) - stops the graphic near the right-hand edge.

  • The expression document.body.clientWidth determines the width of the document.

    This value is obtained on loading and after resizing.

    Hence the use of the onLoad and onResize commands, both of which call the function init().

    The latter assigns the value of the expression to the variable pw.

    This ensures that the graphic stops just before the right-hand edge, regardless of window size.


    Since the counter is incremented by a multiplier - 1.03 - the motion accelerates.

    A timer is used to control the counter, setting a pause of 10 milliseconds between each increment.


    When the Stop button is clicked, function stop() clears the timer, and the motion ceases.

    Clicking Start again will continue the motion from the current position.


    When the Reset button is clicked, the timer is again cleared, and the image is returned to its start position.

    This function is also called whenever the browser is resized.


    Vertical animation can also be achieved, by changing the left parameter to top.


    Try It Out

    Click the buttons and see what happens :




    © 2001 CyberSchool