1. Home
  2. Computing & Technology
  3. JavaScript
This is a web page object.

Web Page Animation

11. Reversing Direction

clr gif

So far once the move link has been selected once and the object moved to a new location, further selection of the move link has no effect. In this tutorial we are going to amend the script so that selecting the link again will move the object back to its original position.

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');
}

Here we add a startPos variable to go with our endPos variable so that we can swap them over after the move in order to move back. We also adjust the alignment of the end position so that it is an even number of pixels offset from the start position. The endPos -= (endPos-startPos) % 2; calculation will subtract one from the end position if the distance is an odd number and leave it alone if it is even. Since we are moving the object by two pixels each time this will remove the possibility of the object going one pixel past the end position and getting stuck where it ends up moving constantly from one side of the destination to the other without ever reaching it.

The moveit function remains unchanged but we need to amend the mover function to handle movement in both directions.

function mover() {
if (yyy < endPos) {
yyy +=2; moveit(); setTimeout('mover()',25);}
else if (yyy > endPos) {
yyy -=2; moveit(); setTimeout('mover()',25);}
else {endPos = startPos; startPos = yyy;}

}
window.onload = start;
window.onscroll = moveit;

The first if statement handles the movement from the original start position to the end position as before. The second if statement similarly handles movement in the opposite direction. When the object finishes moving to the end position then neither of these conditions is satisfied and the code swaps the start and end positions around ready to move in the opposite direction the next time the link is selected.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.