Donnerstag, April 20, 2006

Simple sliding sample to move HTML elements around

Moving HTML objects to new positions is not hard to implement. You can use absolute positioning and just set the style attributes left and top to the new values but it doesn't look cool if the objects use this kind of hyper speed: the eyes cannot follow and there may be a confusing effect of a sudden rearrangement.

Moving objects more slowly can be simulated by moving them using several steps and only a small distance at once. All we need is a timer to start the next step after the current position is rendered, a little bit of algebra and a heuristic to find the right distance for one step.

Because no local variables can be used when executing timer scripts we declare 4 global variables that hold all the information we need when the next step is to be started:

var slidingTimer = null; // the current running timer object
var slidingTarget = null; // the moving object
var slidingLeft = null; // the target left position
var slidingTop = null; // the target top position

Starting a sliding movement can be done by calling the startSlidePos function with 3 parameters: the object that should be moved, the new left and the new top coordinate. You can also refer the object by using the unique id.

onclick="startSlidePos('i', 10, 270)"

Every timer event now calculates the remaining vector but takes no more than 20 pixel length or a third of it whatever is shorter. Only if the target is very close the object will be positioned exactly:

// calc the remaining vector
dx = slidingLeft - left;
dy = slidingTop - top;

// calc the movement length along the vector
len = Math.sqrt(dx * dx + dy * dy);
delta = Math.min(20, len/3);

if (len <= 2) {
  // snap exactly
  left = slidingLeft;
  top = slidingTop;

} else {
  left += Math.round(dx * delta / len);
  top += Math.round(dy * delta / len);
} // if

Using this calculation the movement gets slower at the end when the target is almost reached.

You can see the full source code by using the view source functionality of your browser or in the right upper corner of the page.

You can find the sample live at:

Keine Kommentare: