JavaScript tutorial:
Moving an image

 

Use your JavaScript Editor to open MoveImage.htm (in the Tutorial folder inside your JavaScript Editor folder) and examine the code. The MoveImage.htm file, associated resources and other examples used by this part of the tutorial can also be downloaded from: https://c-point.com/javascript_tutorial/JavaScript_tutorial_examples.zip

The script animates the image by moving it from its initial location to the specified location.

To run the code click on the Show Internal Viewer button, or
Click here to open MoveImage.htm in the browser.

The key to moving an object is the function moveObjRight(obj):

function moveObjRight(obj)
{
obj.style.left=Hmove;
Hmove+=2;
if(Hmove<100)
window.setTimeout("moveObjRight(" +obj.id+ ");", 0);
}

The function moves an object by 2 pixels and calls the timer function setTimeout(), which calls the moveObjRight() function after a certain period of time has passed. This process is repeated until the animation has been completed.

Note the way setTimeout() is passing a parameter to moveObjRight(): " +obj.id+ "
This means that what is inside the +..+ marks is a variable.

The image that is being animated, JavaScript.gif, uses absolute positioning: that way it is easier to plan the action.

 

Next