February 13, 2000 - Moving A DHTML | WebReference

February 13, 2000 - Moving A DHTML

Yehuda Shiran February 13, 2000
Moving A DHTML
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

The DHTML's left and top properties are 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. Usually we're working with pixels, so 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.

Learn more about JavaScript animations in Column 18, JavaScript Animations, Part I .