Java Reference
In-Depth Information
Next in the script block is the doAnimation() function, which performs the animation:
function doAnimation() {
var divAdvert = document.getElementById("divAdvert");
var currentLeft = divAdvert.offsetLeft;
var newLocation;
First, you retrieve the divAdvert element with the getElementById() method; you also retrieve the
offsetLeft property and assign its value to the currentLeft variable. You use this variable to check
the content's current position. Next, create a variable called newLocation that will contain the new left
position, but before you assign its value you need to know the direction in which the content is moving:
if (!switchDirection) {
newLocation = currentLeft + 2;
if (currentLeft >= 400) {
switchDirection = true;
}
}
First, check the direction by checking the switchDirection variable. Remember, if it is false , the
animation is moving from left to right; so assign newLocation to contain the content's current position
and add 2 , thus moving the content two pixels to the right.
You then need to check if the content has reached the left position of 400 pixels. If it has, you need to
switch the direction of the animation, and you do this by changing switchDirection to true . So the
next time doAnimation() runs, it will begin to move the content from right to left.
The code to move the element in this new direction is similar to the previous code, except for a few key
differences:
else {
newLocation = currentLeft - 2;
if (currentLeft <= 0) {
switchDirection = false;
}
}
The first difference is the value assigned to newLocation ; instead of adding 2 to the current location,
you subtract 2 , thus moving the content two pixels to the left. Next, check if currentLeft is less than
or equal to 0 . If it is, you know you've reached the ending point of the right‐to‐left movement and need
to switch directions again by assigning switchDirection to be false .
Finally, set the new position of the content:
divAdvert.style.left = newLocation + "px";
}
This final line of the function sets the element's left property to the value stored in the newLocation
variable plus the string "px" .
Search WWH ::




Custom Search