Web Page Animation12. Perpetual Motion |
|
Join the DiscussionWe already know how to set up our object so that it can be moved backwards and forwards between two positions. Instead of having our visitor click on a link each time the object finishes moving in order to get it to move the other way we can make a minor change to the mover function so that the object will move backwards and forwards continuously. Who said perpetual motion eas impossible. Since the object will not be dependent on someone selecting a link to start it moving we'll remove the link from the object and add a call to the mover function into the end of the start function Here is the code in full (apart from the function libraries) with the latest changes highlighted.
var xxx = 0; var yyy = 0;
var startpos = endPos = 0; function start() { var w = objWidth('myobj'); xxx = (pageWidth()-w-20); startPos = yyy = 10; endPos = (pageHeight()-objHeight('myobj'))/2; endPos -= (endPos-startPos) % 2; moveit(); setObjVis('myobj','visible'); mover(); } function moveit() { var x = (posLeft()+xxx) + 'px'; var y = (posTop()+yyy) + 'px'; moveObjTo('myobj',x,y); } function mover() { if (yyy < endPos) { yyy +=2;} else if (yyy > endPos) { yyy -=2;} else {endPos = startPos; startPos = yyy;} moveit(); setTimeout('mover()',25); } window.onload = start; window.onscroll = moveit; Basically all we have done is to move the call to moveit() and the setTimeout from the two if statements to the end of the mover function where they will always be run. This means that once the start and end positions have been swapped that the functions will be called to start moving the object back in the opposite direction automatically. The call to mover() in the start function starts the object moving in the first place without waiting for a link to be selected. |

