JavaScript Animations, Part I: Moving the Element - Doc JavaScript
Moving the Element
We already discussed the left
and top
properties as position indicators. However, we can take advantage of these properties to move an element around the page.
These are read-write properties, so you can also assign them values. In Explorer, left
and top
are string properties. For example, if the top
property in an element's style definition is 400cm
, the value of the element's top
property in JavaScript is 15118 in Navigator, and "400cm"
in Internet Explorer.
When you assign a plain number to an element's left
or top
properties, Internet Explorer assumes its units are pixels. Since we're working with pixels, this behavior meets our needs. We'll move an element around the page by assigning integer values to its left
and top
properties:
function moveTo(x, y) {
this.element.left = x;
this.element.top = y;
}
As you can see, the moveTo()
method of an animation object moves the animated element to a specified position. When invoking this method, you must provide the desired coordinates.
Note that the moveTo()
method simply moves the element to an absolute position. Therefore, it utilizes the basic =
assignment operator. Let's say we want to move an element 100 pixels to the right. We would use the +=
operator, right? Wrong! Remember that Explorer's left
and top
properties carry string values. You can assign them integers, but they will always return strings. In Navigator, these properties hold integer values, so we don't have such a problem. The easiest solution is to use left
and top
for Navigator, and pixelLeft
and pixelTop
for Explorer. But as you'll see, we don't need such a function for our animation library.
Created: April 21, 1998
Revised: April 21, 1998
URL: https://www.webreference.com/js/column18/move.html