Java Reference
In-Depth Information
The preceding code specifies the end point (in this case,
394
) and assigns it to the
endPointX
variable. You can then check to see if the element's
offsetLeft
value is currently less than that of
the end point. If it is, you can continue the animation. This example brings us to the next topic in
content movement: performing the animation.
performing the animation
To perform an animation, you need to modify the
top
and
left
properties of the
style
object incrementally and quickly. You do this with periodic function execution until it's
time to end the animation. To do this, use one of two methods of the
window
object:
setTimeout()
or
setInterval()
. This example uses the
setInterval()
method to periodically
move an element.
animating Content
trY it out
This page moves an element across the page from right to left. Open your text editor and type the
following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 9, Example 6</title>
<style>
#divAdvert {
position: absolute;
font: 12px Arial;
top: 4px;
left: 0px;
}
</style>
</head>
<body>
<div id="divAdvert">
Here is an advertisement.
</div>
<script>
var switchDirection = false;
function doAnimation() {
var divAdvert = document.getElementById("divAdvert");
var currentLeft = divAdvert.offsetLeft;
var newLocation;
if (!switchDirection) {
newLocation = currentLeft + 2;
if (currentLeft >= 400) {
switchDirection = true;
}